C 父进程不使用signal()等待所有子进程退出
程序最初要求用户输入要创建的子进程数。创建子对象后,父对象睡眠并等待其所有子对象通过向SIGCHLD注册的信号处理程序函数“handle_child”终止C 父进程不使用signal()等待所有子进程退出,c,signals,fork,sleep,sigchld,C,Signals,Fork,Sleep,Sigchld,程序最初要求用户输入要创建的子进程数。创建子对象后,父对象睡眠并等待其所有子对象通过向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
#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;
}
我认为对睡眠的调用(30)被SIGCHLD中断中断,因此它在30秒内不会睡眠,而是在调用信号处理程序后立即返回
要想正确,您需要在循环中睡觉:
tosleep = 30;
while (tosleep > 0) {
tosleep = sleep(tosleep);
}
谢谢,这解决了问题!不知道sleep()因信号而中断。。
tosleep = 30;
while (tosleep > 0) {
tosleep = sleep(tosleep);
}