#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);
}
我在上面的程序中,common line 字符串在输出中显示了一次。 但“0”在结果中出现了两次。
即将到来的输出:
common line
01
02
或
common line
02
01
按我的理解,0应该只出现一次?
最佳答案
通过在字符串末尾添加一个换行符,您可以在 fork 之前隐式地刷新输出缓冲区。您的另一个选择是使用 fflush(stdout)
显式刷新它。否则,当您 fork()
时,这两个进程只是吐出之前缓冲区中仍然剩余的内容(在您的情况下,未刷新的缓冲区仍然包含 printf 中的
).num
("%d", num)
关于c - 理解 c 中的 fork,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28971816/