2013-04-06 79 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