我需要捕獲CTRL + C並完成子項,主進程必須等到完成它的東西,然後程序才能完成。 這是我的代碼:以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。這不是可重入的。 – JeremyP