gpt4 book ai didi

c - 为什么我的信号处理程序执行两次?

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:34 26 4
gpt4 key购买 nike

我正在学习 Linux 中的进程间通信,使用 kill() 向休眠的子进程发送信号。这是我的程序:

 8 void func(void);
9 int main(void){
10 int i, j;
11 pid_t status, retpid;
12 signal(17,func);
13 if( i = fork() ){
14 printf("Parent:signal 17 will be sent to child!\n");
15 kill(i, 17);
16 wait(0);
17 printf("child process terminated\n");
18 }
19 else{
20 sleep(10);
21 printf("Child: A signal from my parent is received!\n");
22 exit(0);
23 }
24 }
25 void func(void)
26 {
27 printf("the signal has been sent!\n");
28 }

用gcc编译,程序出现异常,func()执行了两次:

./test4.out
Parent:signal 17 will be sent to child!
the signal has been sent!
Child: A signal from my parent is received!
the signal has been sent!
child process terminated

我分析了结果,然后删除了以下两行:

 16                 wait(0);
17 printf("child process terminated\n");

结果变得正常,只调用了一次 func()。罪魁祸首似乎是 wait() 函数,但为什么它会调用信号处理程序?

最佳答案

您正在向子进程发送信号 17,因此它的处理程序按预期被调用。

信号 17 是 SIGCHLDSIGCHLD 在子进程死亡时发送给父进程。当 child 退出时, parent 的处理程序被调用。这个信号不是来自 parent ;它来自操作系统,用于通知 parent child 的死亡。

关于c - 为什么我的信号处理程序执行两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40435022/

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