该程序最初要求用户输入要创建的子进程的数量。创建孩子后,父母会休眠并等待其所有孩子通过使用 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;
}
我面临的问题是父母经常在没有收获所有孩子的情况下退出。有时程序运行得很好,有时却突然结束。这里到底发生了什么?
错误输出的实例之一:
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:~$