父代码在C中的多进程程序中调用两次

tit*_*ioc 1 c fork process

我一直在学习fork in c,我有这个程序:

 int main(void) {
     int i;
     printf("Start program\n");
     printf("This is parent process %d: %d\n", getpid(), i);
     int pid = fork();
     printf("%d ", pid);
     if(pid == 0) {
       printf("This is process %d: %d\n", getpid(), i);
     } 
   return 0;
 }
Run Code Online (Sandbox Code Playgroud)

这是输出:

Start program
This is parent process 4467: 0
4578 Start program
This is parent process 4467: 0
0 This is process 4578: 0
Run Code Online (Sandbox Code Playgroud)

我不明白为什么父代码被调用两次.

Bas*_*tch 8

stdout是缓冲的.参见例如setvbuf(3).

在做叉子之前你忘了叫fflush(3)(2).作为一个经验法则,你会做的更好fflush(NULL)之前的任何fork().

这可以解释所观察到的行为(因为冲洗两父子进程,例如在程序退出或返回后发生main信息crt0).您可能(在Linux上)使用strace(1)来更准确地了解发生了什么.

BTW, fork(2)可能会失败.你应该处理(即处理pid == -1 (或pid<0)情况......).