76

我希望有人可以阐明如何让父进程等待所有子进程完成,然后再继续分叉。我有我想运行的清理代码,但子进程需要在这发生之前返回。

for (int id=0; id<n; id++) {
  if (fork()==0) {
    // Child
    exit(0);      
  } else {
    // Parent
    ...
  }
  ...
}
4

4 回答 4

82
pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) {
    if ((child_pid = fork()) == 0) {
        //child code
        exit(0);
    }
}

while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait等待进程终止,并返回该子进程的pid. 出错时(例如,当没有子进程时),-1返回。所以,基本上,代码一直在等待子进程完成,直到出现waiting 错误,然后你就知道它们都完成了。

于 2014-05-26T14:52:23.310 回答
37
于 2013-10-19T02:53:30.967 回答
26

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}
于 2013-10-19T02:53:39.880 回答
2

只需使用:

while(wait(NULL) > 0);

这可确保您等待所有子进程,并且只有当所有子进程都返回时,您才转到下一条指令。

于 2021-10-12T21:45:20.980 回答