-2

如何更改程序以使功能function_delayed_1function_delayed_2仅同时执行一次:

 int main(int argc, char *argv[]) {
     printf("message 1.\n");
     fork();
     function_delayed_1();
     function_delayed_2();
     printf("message 2.\n");
 }
4

2 回答 2

2

阅读manfork的页面,并google一些示例fork();,您的代码应如下所示:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
     pid_t pid; // process ID

     printf("message 1.\n");
     pid = fork();
     if (pid < 0) {
         perror("fork");
         return;
     }

     if (pid == 0) {
         function_delayed_1(); // child process
     }
     else {
         function_delayed_2(); // parent process
     }
     printf("message 2.\n");
 }
于 2013-01-02T10:42:19.880 回答
1
int main(int argc, char *argv[]) {
    printf("message 1.\n"); // printed once by parent process
    if(fork())
        function_delayed_1(); // executed by parent process
    else
        function_delayed_2(); // executed by child process

    printf("message 2.\n"); // will be printed twice once by parent & once by child.
}
于 2013-01-03T07:19:14.843 回答