フォーク後に続行する前に、すべての子プロセスが終了するのを親に待機させる方法について、誰かが光を当てることができることを願っています。実行したいクリーンアップ コードがありますが、これが発生する前に子プロセスが返される必要があります。
for (int id=0; id<n; id++) {
if (fork()==0) {
// Child
exit(0);
} else {
// Parent
...
}
...
}
フォーク後に続行する前に、すべての子プロセスが終了するのを親に待機させる方法について、誰かが光を当てることができることを願っています。実行したいクリーンアップ コードがありますが、これが発生する前に子プロセスが返される必要があります。
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<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
が返されます。したがって、基本的に、コードは ing エラーが発生するまで子プロセスが終了するのを待ち続けwait
ます。その後、子プロセスがすべて終了したことがわかります。
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!.");
}
}
使用するだけです:
while(wait(NULL) > 0);
これにより、すべての子プロセスを確実に待機し、すべてが戻ったときにのみ、次の命令に移動します。