如何让父母等待所有子进程完成?

Don*_*llo 41 c operating-system posix fork process

我希望有人可以解释如何让父母等待所有子进程完成后再继续fork之后.我有清理代码,我想运行,但子进程需要返回才能发生这种情况.

for (int id=0; id<n; id++) {
  if (fork()==0) {
    // Child
    exit(0);      
  } else {
    // Parent
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

adr*_*ons 48

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)
Run Code Online (Sandbox Code Playgroud)

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


lon*_*dao 26

POSIX定义了一个函数:wait(NULL)?.它是简写waitpid(-1, NULL, 0);,它将暂停执行调用进程,直到任何一个子进程退出.这里,第一个参数waitpid表示等待任何子进程结束.

在您的情况下,让父母从您的else分支内部调用它.

  • `wait`的联机帮助页说它等待****的一个孩子终止.正如上面提到的@WhozCraig你需要'等待'`n次. (9认同)
  • 我使用 while(wait(NULL) &gt; 0); 以便进程等待其子进程的 **所有** 终止。 (4认同)

Jas*_*chs 22

像这样使用waitpid():

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!.");    
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这并不等待所有的孩子只完成一个孩子的孩子.如果有更多的流程,这将无效. (2认同)
  • 您将如何修改此代码以供父母等待所有孩子完成? (2认同)

小智 5

只需使用:

while(wait(NULL) > 0);
Run Code Online (Sandbox Code Playgroud)

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