11

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?

ammianus
  • 488
  • 7
  • 23

3 Answers3

5

"signum" parameter of "sigaction" system call is an integer value, which does not work as a flag.

As far as I know, there's no way to assign one handler function for several signals in one call.

Kel
  • 7,680
  • 3
  • 29
  • 39
5

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.

Tim
  • 9,171
  • 33
  • 51
  • Thanks, that is a good idea. I guess I can continue to enumerate the signals I would like to catch, since I am new to C I was curious if I was missing something. – ammianus Oct 25 '10 at 19:58
2

Is this the correct way to set up this type of handling?

Not quite - it's not safe to use printf() inside a signal handler, but you can still use write() to stdout or stderr.

Dan Yard
  • 147
  • 1
  • 5