Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching signal inside its own handler

#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..

like image 624
Abhijeet Rastogi Avatar asked Mar 10 '10 16:03

Abhijeet Rastogi


People also ask

Can a SIGSEGV signal be caught?

SIGSEGV is usually caused by using uninitialized or NULL pointer values or by memory overlays. By default, SIGSEGV causes program termination with an appropriate ABEND code (0C4 for a protection error or 0C5 for an addressing error). The SIGSEGV signal cannot be ignored.

What happens when we register a handler for a signal?

In the handler function, the signal handler re register to SIG_DFL for default action of the signal. When user typed Ctrl+C for second time, the process is terminated which is the default action of SIGINT signal.

How do signal handlers work?

A signal handler is a function which is called by the target environment when the corresponding signal occurs. The target environment suspends execution of the program until the signal handler returns or calls longjmp() . Signal handlers can be set with signal() or sigaction() .

Can a signal handler be interrupted by another signal?

(The handler can explicitly unblock the signal using sigprocmask , if you want to allow more signals of this type to arrive; see Process Signal Mask.) However, your handler can still be interrupted by delivery of another kind of signal.


1 Answers

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

like image 94
Tronic Avatar answered Oct 01 '22 02:10

Tronic