父母如何等待所有子进程完成然后在收到SIGINT时退出?

时间:2011-09-25 13:51:45

标签: c unix fork signals

我正在用C编写一个多进程程序。

我希望父进程可以等待所有子进程完成然后退出 它接收SIGINT。

我有两个问题。

  1. 父母如何记录分叉的子进程的每个pid。 在录制功能运行之前,子进程可能会完成 主要过程。

  2. 如果父母不知道它有多少子进程。他怎么能等 所有子进程完成。

  3. 提前致谢。

2 个答案:

答案 0 :(得分:1)

您在分叉子进程时记录子进程的pid(如果需要)。 在pid = 0的循环中调用waitpid,它将返回退出的进程的pid或返回-1,如果errno = ECHILD则没有剩余的奴隶。

答案 1 :(得分:0)

继续在循环中调用wait(2)。每次wait()返回时,您都会返回已退出子项的PID及其状态。状态将告诉您,它是正常退出(带退出代码)还是由于信号退出。这样的事情(未经测试):

#include <sys/types.h>
#include <sys/wait.h>
...
pid_t    pid;
int      status;
...
while ((pid = wait(&status)) > 0) {
        printf("Child %lu ", (unsigned long)pid);
        if (WIFEXITED(status))
                printf("exited with status %d\n", WEXITSTATUS(status));
        else if (WIFSIGNALED(status))
                printf("killed by signal %d\n", WTERMSIG(status));
        else if (WIFSTOPPED(status))
                printf("stopped by signal %d\n", WSTOPSIG(status));
        else if (WIFCONTINUED(status))
                printf("resumed\n");
        else
                warnx("wait(2) returned for no discernible reason");
}
相关问题