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

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

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

 pid_t child_pid, wpid; int status = 0; //Father code (before child processes start) for (int id=0; id 0); // this way, the father waits for all the child processes //Father code (After all child processes end) 

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

在您的情况下,让父母从您的else分支中调用它。

像这样使用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!."); } }