C,进程,分叉

时间:2013-01-02 10:28:26

标签: c fork

如何更改程序,使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");
 }

2 个答案:

答案 0 :(得分:2)

阅读fork的man页面,并查看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");
 }

答案 1 :(得分: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.
}