C语言 如何让父进程等待所有子进程完成?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19461744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make parent wait for all child processes to finish?
提问by Donatello
I'm hoping someone could shed some light on how to make the parent wait for ALLchild processes to finish before continuing after the fork. I have cleanup code which I want to run but the child processes need to have returned before this can happen.
我希望有人可以阐明如何让父进程等待所有子进程完成,然后再继续分叉。我有我想运行的清理代码,但在这发生之前子进程需要返回。
for (int id=0; id<n; id++) {
if (fork()==0) {
// Child
exit(0);
} else {
// Parent
...
}
...
}
回答by adrisons
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)
waitwaits for achild process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1is 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.
wait等待一个子进程终止,并返回子进程的pid。出错时(例如,当没有子进程时),-1返回。所以,基本上,代码一直在等待子进程完成,直到waiting 错误出来,然后你就知道它们都完成了。
回答by xxx7xxxx
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 waitpidindicates wait for any child process to end.
POSIX 定义了一个函数:wait(NULL);. 它是 的简写waitpid(-1, NULL, 0);,它将暂停调用进程的执行,直到任何一个子进程退出。这里,第一个参数waitpid表示等待任何子进程结束。
In your case, have the parent call it from within your elsebranch.
在您的情况下,让父级从您的else分支内调用它。
回答by Jason Enochs
Use waitpid() like this:
像这样使用 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!.");
}
}

