Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to have multiple signal handlers for same signal?

Tags:

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?

like image 531
Lunar Mushrooms Avatar asked Jun 14 '13 07:06

Lunar Mushrooms


People also ask

Can you have multiple signal handlers?

Only one signal handler can be installed per signal.

Do signal handlers run concurrently?

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.

Can signal handlers be interrupted by other signal handlers?

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.

Are signal handlers per thread or per process?

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.


2 Answers

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);
like image 184
Shahbaz Avatar answered Oct 01 '22 20:10

Shahbaz


Only one signal handler can be installed per signal. Only the latest installed handler will be active.

like image 40
Bryan Olivier Avatar answered Oct 01 '22 20:10

Bryan Olivier