【发布时间】:2023-12-29 06:45:02
【问题描述】:
我需要捕获 CTRL+C 并完成子进程,主进程必须等到完成它的东西,然后程序必须完成。 这是我的代码:
void sigint_handler()
{
/*do something*/
printf("killing process %d\n",getpid());
exit(0);
}
int main ()
{
signal(SIGINT, sigint_handler);
printf ("This is the parent. PID=%d\n",getpid ());
int num_children = 4;
int i;
while (1){
for (i=0; i<num_children ;i++){
if (fork()==0){
printf ("This is children %d\n",getpid());
sleep(1);
exit(0);
}
}
//Rest Parent code
sleep (1);
printf ("This is the parent again %d, children should have finished\n",getpid());
//Do stuff
}
}
这是输出:
This is the parent. PID=19317
This is children 19318
This is children 19319
This is children 19321
This is children 19320
^Ckilling process 19321
killing process 19320
killing process 19317
killing process 19318
killing process 19319
我该如何处理这个¿?我不想杀父母,只杀孩子,提前谢谢你!
【问题讨论】:
-
永远不要在信号处理程序中使用 printf。它不是可重入的。
标签: c signals fork kill-process