Parent 进程不等待所有 children 使用 signal() 退出

Parent process does not wait for all children to exit using signal()

该程序最初要求用户输入要创建的 child 个进程的数量。创建 children 后,parent 休眠并等待其所有 children 通过向 SIGCHLD 注册的信号处理函数 'handle_child' 终止。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int to_kill;

void handle_child(int sig)
{
    pid_t id = wait(NULL);
    printf("Reaped child with PID = %d\n",id);
    --to_kill;
    if(to_kill == 0){
        printf("~All children have been reaped successfully.. parent will now exit~\n");
        exit(0);
    }
}

int main()
{
    pid_t id, parent_id = getpid();
    int children, i;
    signal(SIGCHLD, handle_child);
    printf("Enter number of child processes to spawn: ");
    scanf("%d",&children);
    to_kill = children;
    for(i = 0; i < children; ++i){
        id = fork();
        if(id == 0){
            printf("New child with pid = %d\n",getpid());
            sleep(2);
            return 0;
        }
        sleep(1);
    }
    sleep(30);
    return 0;
}

我面临的问题是 parent 经常在没有收获其所有 children 的情况下退出。程序有时运行得很好,有时突然结束。这里到底发生了什么?

错误输出的实例之一:

Enter number of child processes to spawn: 4
New child with pid = 6458
New child with pid = 6459
Reaped child with PID = 6458
New child with pid = 6461
Reaped child with PID = 6459
New child with pid = 6462
Reaped child with PID = 6461
nishad@nishad-Lenovo-B575:~$

我认为对 sleep(30) 的调用被 SIGCHLD 中断中断,因此它不会休眠 30 秒,而是在调用信号处理程序后立即 return。

要做到正确,您需要循环睡眠:

tosleep = 30;
while (tosleep > 0) {
    tosleep = sleep(tosleep);
}