2014-06-27 57 views
0

任何人都可以解釋爲什麼執行包含「這裏」行了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上,那會是一個問題嗎?

+0

使用該網站運行它實際上運行在* nix機器上。 – ooga

+0

是的,我知道,但我認爲值得一提的是它不是本地的 –

+0

就像ooga說的那樣,它與輸出緩衝區有關。這裏是一個更詳細的解釋http://stackoverflow.com/questions/2530663/printf-anomaly-after-fork – Yongzhi

回答

2

叉創建一個幾乎相同的過程,包括輸出緩衝區。如果這些不在fork之前刷新,則兩個進程都可能最終打印內容。嘗試在父母的printf後面輸入fflush(stdout);

+0

是的,這確實奏效。謝謝 –

0

它不應該得到你提到的輸出。正如我測試你的代碼我的輸出是以下

11194:0這裏

11194:1這裏

11195:0

11196:1

也許你應該重新編譯,並再試一次?

+0

你在什麼系統上運行這個? – ooga

+0

14.04 ubuntu ... – Yongzhi

+0

我明白了。但是,在不同的系統上它有所不同,具體取決於輸出緩衝如何工作。 – ooga