Catching signal inside its own handler Catching signal inside its own handler unix unix

Catching signal inside its own handler


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.


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


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?