简体   繁体   English

C语言中的嵌套信号处理程序

[英]Nested signal handlers in C

I want to work on signal handlers in the context of two independent processes namely writer and reader for notification. 我想在两个独立的进程(即用于通知的编写器和读取器)的上下文中处理信号处理程序。 The writer sends a first signal SIGUSR1 to the reader which loops till it hears the second signal SIGUSR2 from the writer. 写入器将第一个信号SIGUSR1发送到读取器,读取器将循环播放直到听到来自写入器的第二个信号SIGUSR2。

reader.c reader.c

static volatile sig_atomic_t done_waiting; 

int handler1(int signal){
    done_waiting = 0;
     while( !done_waiting ){
            (void)fprintf(stdout, " reader waiting for sigusr2: done_waiting = %d\n", done_waiting );
    }
(void)fprintf(stdout, " reader received sigusr2 \n);
}

int handler2 (int signal){
         done_waiting = 1;
}

main(){
    signal(SIGUSR1, handler1);
    signal(SIGUSR2, handler2);
    sleep(5); // sleep till we start worker
}

In writer.c, signals are sent to the reader as 在writer.c中,信号作为

main(){
    kill(pid_reader, SIGUSR1);
    sleep(5);
    kill (pid_reader, SIGUSR2);
}

When I execute reader first followed by worker, the program quits at the while loop. 当我先执行阅读器,然后执行worker时,程序将在while循环中退出。 And the writer prints that "No matching processes belonging to you were found". 然后作者打印出“未找到属于您的匹配进程”。

Is nesting signal handlers allowed and if yes, is it recommended? 是否允许嵌套信号处理程序?如果是,建议这样做吗? Also, is there any another alternative mechanism for writer to notify reader that it is ready? 另外,写者是否还有其他替代机制可以通知读者它已经准备好了?

Is maybe nested signals actually what you meant, not nested signal handlers ? 也许嵌套信号实际上是您的意思,而不是嵌套信号 处理程序吗? To clarify, what will happen if a SIGUSR2 is received while the handler for SIGUSR1 is executing, is that what you mean ? 澄清一下,如果在执行SIGUSR1的处理程序时收到SIGUSR2会发生什么,这是您的意思吗? I assume so, 我想是这样

I tested your code, with some modifications, to get the pid for the reader process into the writer process I used the args to main. 我测试了您的代码,并进行了一些修改,以使读取器进程的pid进入使用args进行维护的写入器进程。

The results I get is. 我得到的结果是。

  1. First reader is quiet 第一读者安静
  2. After receiving SIGUSR1 it starts continuously writing that it waits for SIGUSR2 收到SIGUSR1后,它开始连续写入以等待SIGUSR2
  3. When receiving SIGUSR2, it prints "reader received SIGUSR2" 收到SIGUSR2时,它显示“阅读器已收到SIGUSR2”

This indicates that it is possible to have nested signals. 这表明可能有嵌套信号。 However I would not say it is recommended as an intentional design. 但是我不会说建议将其作为有意设计。 As mentioned in the comments, you should do as little as possible in the signal handlers, definitely not loop in a while-loop. 如评论中所述,您应该在信号处理程序中做尽可能少的事情,绝对不要在while循环中循环。 And as also mentioned in the comments, be very careful what functions you call in signal-context, printf() is not OK, even though it may seem to work fine. 而且,正如评论中所提到的,要非常小心在信号上下文中调用的函数,printf()不好,尽管它似乎可以正常工作。

Tested on Linux, with the ancient kernel 3.16 and gcc 4.9 在Linux上测试,使用古老的内核3.16和gcc 4.9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM