父进程不等待所有子进程使用signal()退出

时间:2015-04-13 07:59:03

标签: c signals fork sleep sigchld

程序最初要求用户输入要创建的子进程数。在创建子节点之后,父节点会休眠并等待其所有子节点通过信号处理函数终止' handle_child'在SIGCHLD注册。

#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;
}

我面临的问题是父母经常退出而没有收获所有孩子。有些时候程序运行得很好,有时它会突然结束。这到底发生了什么?

错误输出的一个实例:

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:~$

1 个答案:

答案 0 :(得分:3)

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

要做到正确,你需要在一个循环中睡觉:

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