2015-10-13 81 views
1

我有一個循環創建'n'子進程。進程進入一個單獨的程序,睡眠'x'秒,然後返回退出狀態'x'。問題是當我嘗試等待每個單獨的進程時。看起來,我的wait()調用等待最後一個進程,然後程序退出。我希望這樣,以便哪個孩子退出,我可以打印他們的信息,然後等待下一個孩子退出並打印他們的信息......等等。wait()不等待每個孩子

代碼:

int main() 
{ 
     char input[12]; 
     int n, i, ch; 
     pid_t pid; 
     int status={0}; 

     printf("Enter an integer: "); 
     fgets(input, 12, stdin); 
     if (input[10] == '\n' && input[11] == '\0') { while ((ch = fgetc(stdin)) != EOF && ch != '\n'); } 
     rmnewline(input); 

     n = atoi(input); 

     for(i=0; i<=n-1; i++) 
     { 
     pid = fork(); 
     if(pid == 0) 
     execl("/home/andrew/USP_ASG2/sleep", "sleep", NULL); 
     } 

     for(i=0; i<=n-1; i++) 
     { 
     wait(&status); 
     if(WIFEXITED(status)) 
     { 
      int exitstat = WEXITSTATUS(status); 
      printf("Child %d is dead with exit status %d\n", pid, exitstat); 
     } 
     } 
} 

輸出:

In child 15930 
In child 15929 
In child 15928 
Child 15930 is dead with exit status 5 
Child 15930 is dead with exit status 5 
Child 15930 is dead with exit status 5 
+0

除此之外:作爲一種風格,'i <= n-1'會更清晰,因爲'i

+0

@WeatherVane No.對於基於零的數組偏移,'for(i = 0; i < n; i ++)'是在C中編寫'for'循環的標準方式。只需要Google「c for循環」。看到很多例子:http://www.codingunit.com/c-tutorial-for-loop-while-loop-break-and-continue http://stackoverflow.com/questions/4604500/use-of-for-in -ac-sharp-application http://www.tutorialspoint.com/cprogramming/c_for_loop.htm http://www.thegeekstuff.com/2012/12/c-loops-examples/此外,省略減法可能導致性能略有改善,特別是在像x86這樣需要註冊的架構上。 –

+1

@AndrewHenle你確定你看過我的評論corerctly?如果'n == 0',循環控制'i <= n-1'在無符號時會發生什麼。我寫得「更清晰」,而不是「比」更清晰。 –

回答

1

你忘了捕捉wait()的返回值,所以pid仍然包含您分叉了最後進程的PID。

這樣做:

pid = wait(&status); 

,你會得到預期的輸出。

+0

謝謝你清理那個!儘管所有的孩子仍然在同一時間以同樣的「隨機」退出狀態退出。編輯:我目前正在改變隨機數的種子如何生成,因爲這可能是問題。 –

+1

@AndrewRicci當你fork()時,子進程獨立於父進程和任何其他子進程運行。它們都是由操作系統分開安排的,所以你無法控制每一個結束的時間而不使用管道,信號或共享內存互斥。退出值完全取決於子進程。 – dbush

+0

他們執行的程序用'srand(time(NULL))生成一個隨機數;''然後在0到9之間隨機選擇一個時間。它不能控制它,只是它們都應該在不同的時間退出。 –