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

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


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.


As you could see in the man page for sigaction, the new signal handler replaces the old one and the old one is returned.

If you have two unused signals (say SIGUSR1 and SIGUSR2), assign those signals the two signal handlers for SIGINT. Then you may write your own Signal Handler for SIGINT and from that, you may raise the needed unused signal as per you want.