I have two shared libraries linked to my test application. Both of the libraries have signal handlers for SIGINT
.
Is it valid to have multiple signal handlers for same signal? Which order the handlers will execute when I generate a SIGINT
signal?
Only one signal handler can be installed per signal.
Though, if you have multiple threads, and the signal is not blocked in the other threads, a signal handler might very well be run concurrently within several threads.
Signal handlers can be interrupted by signals, including their own. If a signal is not reset before its handler is called, the handler can interrupt its own execution. A handler that always successfully executes its code despite interrupting itself or being interrupted is async-signal-safe.
signal is a per process call, not a per thread one, if you call it it sets the handler for all threads in the process.
As said by others, only one signal handler can be set, which is the last one. You would then have to manage calling two functions yourself. The sigaction
function can return the previously installed signal handler which you can call yourself.
Something like this (untested code):
/* other signal handlers */
static void (*lib1_sighandler)(int) = NULL;
static void (*lib2_sighandler)(int) = NULL;
static void aggregate_handler(int signum)
{
/* your own cleanup */
if (lib1_sighandler)
lib1_sighandler(signum);
if (lib2_sighandler)
lib2_sighandler(signum);
}
... (later in main)
struct sigaction sa;
struct sigaction old;
lib1_init(...);
/* retrieve lib1's sig handler */
sigaction(SIGINT, NULL, &old);
lib1_sighandler = old.sa_handler;
lib2_init(...);
/* retrieve lib2's sig handler */
sigaction(SIGINT, NULL, &old);
lib2_sighandler = old.sa_handler;
/* set our own sig handler */
memset(&sa, 0, sizeof(sa));
sa.sa_handler = aggregate_handler;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
Only one signal handler can be installed per signal. Only the latest installed handler will be active.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With