Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is correct way to have single Signal Handler function for multiple Signals?

Tags:

c

posix

signals

What is the best way in C on Linux for setting up a program that can handle multiple POSIX-signals with the same function?

For example in my code I have a handler function that I want to generically call when ever a signal is caught to perform some actions:

/* Exit handler function called by sigaction */
void exitHandler( int sig, siginfo_t *siginfo, void *ignore )
{
  printf("*** Got %d signal from %d\n", siginfo->si_signo, siginfo->si_pid);
  loopCounter=0;

  return;
}

I have set up two signals to catch by having individual sigaction calls for each signal:

/* Set exit handler function for SIGUSR1 , SIGINT (ctrl+c) */
struct sigaction act;
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = exitHandler;
sigaction( SIGUSR1, &act, 0 );
sigaction( SIGINT, &act, 0 );

Is this the correct way to set up this type of handling? Is there any other way where I don't have to enumerate all the possible signal numbers?

like image 974
ammianus Avatar asked Oct 24 '10 16:10

ammianus


People also ask

Can you have multiple signal handlers?

Only one signal handler can be installed per signal.

Can each thread have its own signal handler?

There is no way to install separate signal handlers for each thread, but the signal handler for a signal may be able to examine which thread it's running in.

Are signal handlers shared across threads?

All threads in a process share the set of signal handlers set up by sigaction(2) and its variants. A thread in one process cannot send a signal to a specific thread in another process.


1 Answers

I can't see how you can straightforwardly set a single handler for all signals. However, you can get fairly close by using sigfillset() to generate a set containing all valid signal numbers, and then iterate over possible signal numbers using sigismember() to determine whether that number is in the set, and set a handler if so. OK, I can't see a method of determining what the maximum possible signal number is, so you might have to guess a suitable maximum value.

like image 141
Tim Avatar answered Oct 13 '22 00:10

Tim