gpt4 book ai didi

在 C 中捕获信号并杀死所有 child

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:46 24 4
gpt4 key购买 nike

我需要捕获 CTRL+C 并完成 child ,主进程必须等到完成它的东西,然后程序必须完成。这是我的代码:

 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

我该如何处理这个 ¿?我不想杀死 parent ,只想杀死 child ,在此先感谢您!

最佳答案

现在像这样好多了:

    void sigint_handler()
{
/*do something*/
printf("killing process %d\n",getpid());
exit(0);
}

int main ()
{
int num_children = 4;
int i, pid, status;
printf ("This is the parent. PID=%d\n", getpid());

while (1) {
for (i = 0; i < num_children; i++) {
if ((pid = fork()) == 0) {
signal(SIGINT, sigint_handler);
printf("This is children %d\n", getpid());
sleep(1);
exit(0);
}
}

// Rest Parent code
sleep (1);
waitpid(pid, &status, 0);
printf ("This is the parent again %d, children should have finished\n", getpid());
}
}

它首先杀死了 child ,但 waitpid 似乎什么也没做,这是输出:

This is the parent. PID=20048
This is children 20049
This is children 20050
This is children 20051
This is children 20052
This is the parent again 20048, children should have finished
This is children 20053
This is children 20054
This is children 20056
This is children 20055
^Ckilling process 20056
killing process 20055
killing process 20053
killing process 20054

而我想要的是在最后打印:This is the parent again 20048, children should have finished and then finish.非常感谢

关于在 C 中捕获信号并杀死所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23137091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com