試試這個:
void exit_message (void)
{
// use write to have an unbuffered output
char m[100];
sprintf (m, "%d exit\n", getpid());
write (1, m, strlen(m));
}
main(){
atexit (exit_message);
printf("%d test 1\n",getpid());
fork();
printf("%d test 2\n",getpid());
}
輸出將是這樣的:
14866 exit // <- parent process flushes its output at exit
14866 test 1 // <- parent process: 1st printf
14866 test 2 // <- parent process: 2nd printf
14867 exit // <- forked process flushes its output at exit
14866 test 1 // <- forked process: unflushed parent process output buffer
14867 test 2 // <- forked process: 2nd printf
我們可以看到用兩岔過程中所做的唯一的printf是最後一個,符合市場預期。
上一行是stdout輸出緩衝區的重影,它在刷新之前被fork()重複。
製作標準輸出緩衝
main(){
atexit (exit_message);
setvbuf(stdout, NULL, _IONBF, 0);
printf("%d test 1\n",getpid());
fork();
printf("%d test 2\n",getpid());
}
如果加上`fflush(標準輸出)擺脫了鬼
14866 test 1 // <- parent process: 1st printf
14866 test 2 // <- parent process: 2nd printf
14866 exit // <- parent process exits
14867 test 2 // <- forked process: 2nd printf
14867 exit // <- forked process exits
會發生什麼的;''之前叉();'? – immibis
你錯過了'unistd.h'頭文件。 – Mat
@KarolyHorvath +1輸出是'test1 \ ntest2 \ ntest2' – atupal