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

我希望有人能够解释一下,如何让父进程等待 全部子进程完成后再继续分叉。我有清理代码,我想运行,但子进程必须返回才能发生这种情况。

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

POSIX defines a function: wait(NULL);. It's the shorthand for waitpid(-1, NULL, 0);, which will suspends the execution of the calling process until any one child process exits. Here, 1st argument of waitpid indicates wait for any child process to end.

In your case, have the parent call it from within your else branch.

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!.");
}
}
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 waits for a child process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

Just use:

while(wait(NULL) > 0);

This ensures that you wait for ALL the child processes and only when all have returned, you move to the next instruction.