2013-04-06 78 views
-1

我想統計用1,10和fork()si執行的進程的數量。該程序在Linux中執行。我真的不知道如何使用wait或WEXITSTATUS,我花了數小時在論壇上,仍然沒有得到它。有人能幫助我嗎?C:進程如何在linux中進行通信

感謝, 德拉戈什

#include <sys/types.h> 
#include <unistd.h> 
#include <sys/wait.h> 
#include <stdio.h> 
#include <stdlib.h> 

int nr = 1; 

int main() 
{ 


    int pid; 
    int i; 
    int stare; 
    for(i = 1; i<=10 ; i++) 
    { 

     pid = fork(); 

     if(pid !=0) 
     { 

      //parent 
      wait(&stare); 
      nr = nr + stare; 


     } 
     else 
     { 
      //child 
      nr++; 
      stare = WEXITSTATUS(nr); 
      exit(nr); 

     } 
    } 

    printf("\nNr: %d\n", nr); 

}    
+2

'WEXITSTATUS(nr);'只對父級有意義。在孩子的過程中,這是毫無用處的。 (孩子沒有「看見」狀態(除了第二個孩子,他們會看到第一個孩子的狀態等) – wildplasser 2013-04-06 11:23:07

+4

在論壇上花費幾小時?爲什麼不花幾分鐘時間在[手冊頁](http:// publib .boulder.ibm.com/infocenter/tpfhelp/current/topic/com.ibm.ztpf-ztpfdf.doc_put.cur/gtpc2/cpp_wait.html#cpp_wait)? – 2013-04-06 11:24:51

回答

1

WEXITSTATUS宏在過程中用來獲取wait調用後退出狀態。

在子進程中,只需返回nr(或將其作爲參數調用exit就足夠了)。

在父使用WEXITSTATUS這樣的:

if (wait(&stare) > 0) 
{ 
    if (WIFEXITED(stare)) 
     nr += WEXITSTATUS(stare); 
} 

,否則退出狀態是無效的,我們必須使用WIFEXITED檢查。

+1

要正確,只應使用'WEXITSTATUS'過程正常退出(請參閱我上面的評論中的鏈接) – 2013-04-06 11:25:31

+0

@KerrekSB當然,謝謝餘下的。 – 2013-04-06 11:27:30