任何人都可以解釋爲什麼執行包含「這裏」行了5次,究竟是如何在程序運行,因爲我似乎不明白我是如何得到這個輸出瞭解UNIX叉
輸出:
12958: 0 here
12959: 0
12958: 0 here
12958: 1 here
12960: 1
12958: 0 here
12958: 1 here
代碼:
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(){
int i;
for(i=0; i<2; i++){
printf("%d: %d here\n", getpid(), i);
if(fork()==0){
printf("%d: %d\n", getpid(), i);
exit(0);
}
}
for(i=0; i<2; i++){
wait(0);
}
return 0;
}
編輯:因爲我跑我的電腦我用這個網站link檢查代碼在Windows上,那會是一個問題嗎?
使用該網站運行它實際上運行在* nix機器上。 – ooga
是的,我知道,但我認爲值得一提的是它不是本地的 –
就像ooga說的那樣,它與輸出緩衝區有關。這裏是一個更詳細的解釋http://stackoverflow.com/questions/2530663/printf-anomaly-after-fork – Yongzhi