Catching signal inside its own handler

2020-03-10 05:45发布

#include<stdio.h>
#include<signal.h>

void handler(int signo)
{
    printf("Into handler\n");
    while(1);
}
int main()
{
    struct sigaction act;
    act.sa_handler = handler;
    act.sa_flags = 0;
    sigemptyset(& act.sa_mask);
    sigaction(SIGINT, &act, NULL);
    while(1);
    return 0;
}

After catching the KeyboardInterrupt once, when I press "Ctrl+C" again, SIGINT is not handled... I intend that "Into handler" should be printed each time I press "Ctrl+C".

I want to catch SIGINT inside the "SIGINT handler()" itself..

5条回答
Explosion°爆炸
2楼-- · 2020-03-10 05:51

What you are doing seems like a very bad idea, though, and it might be better to simply set a flag from the handler and return from it, and then do the printing from main.

You need to set SA_NODEFER or otherwise re-enable the signal within the signal handler itself because otherwise the signal gets blocked or switched back to its default behavior right before the call to the handler.

Calling printf from a signal handler is undefined behavior. It may crash your program. The list of functions that you actually can safely call from a signal handler is very limited. I need a list of Async-Signal-Safe Functions from glibc

查看更多
放荡不羁爱自由
3楼-- · 2020-03-10 05:55

You need to set SA_NODEFER on sa_mask to catch the same signal as the one you're currently handling:

SA_NODEFER: Do not prevent the signal from being received from within its own signal handler. SA_NOMASK is an obsolete, non-standard synonym for this flag.

查看更多
可以哭但决不认输i
4楼-- · 2020-03-10 05:56

Using the printf function within a signal handler is not exactly a good idea to use as it can cause behavior that is undefined! The code sample is missing a vital bit for the signal handler to work....Have a look at my blog about this here on 'Q6. How to trap a Segmentation fault?'

Also, you need to replace the while loop with something more robust as a way to quit the program while testing the signal handler...like...how do you quit it?

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-03-10 05:57

You can use something like this instead of printf:

const char *str = "Into handler\n";
write(1, str, strlen(str));

The function write(..) is safe to be called from signal hanlder. Don't forget to include unistd.h header to use it.

查看更多
太酷不给撩
6楼-- · 2020-03-10 06:13

The "while(1)" in handler is preventing the first service call from ever returning. Remove that and subsequent interrupts should cause handler to be called again.

An interrupt service routine should not prevent the calling thread from returning.

查看更多
登录 后发表回答