理解 c 中的 fork

understanding fork in c

#include <stdio.h>
int num = 0;
int main(int argc, char*argv[]){
   printf("common line\n");  
   printf("%d", num); 
   int pid;
   pid = fork();
   if(pid == 0){       /*child*/
      num = 1;
   } else if(pid > 0){  /*parent*/
      num = 2;
   }
   printf("%d\n", num);
}

我在上面的程序中,公共行 字符串在输出中显示一次。 但是“0”在结果中出现了两次。

即将输出:

common line
01
02

common line
02
01

按我的理解,0应该只来一次吧?

通过在字符串末尾添加一个换行符,您可以在分叉之前隐式地刷新输出缓冲区。您的另一个选择是使用 fflush(stdout) 显式刷新它。否则,当您 fork() 时,两个进程都只是吐出之前仍留在缓冲区中的内容(在您的情况下,未刷新的缓冲区仍包含 printf("%d", num) 中的 num)。