0

I'm programing a multithreaded program that needs to intercept system signals (such as SIGINT). I would like to know if there is a normalized way to "catch" these signals like:

  • A Signal is sent, may any thread receive it or only the main() one ?
  • Is there a Posix rule or a programming idiom that specifies how to handle this ?
Caribou
  • 2,070
  • 13
  • 29
Zaghp
  • 23
  • 3
  • If no thread ever blocked any signal, any thread might receive any signal. A signal is received once or never per process. Referring '*never*': For successively sent signals of the same type all but the first might be swallowed away by the OS. Further reading: `man sigaction` – alk Nov 07 '12 at 12:37
  • Here is an article with examples describing Linux signals. http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/ – Richard Chambers Nov 07 '12 at 12:39
  • Reading up on the actual system call `signal(2)` would also be productive. – eh9 Nov 07 '12 at 12:40
  • Here is a stack overflow question on multi-threading and signals: http://stackoverflow.com/questions/5282099/signal-handling-in-pthreads and here is the signal man page with links to other associated man pages http://www.kernel.org/doc/man-pages/online/pages/man7/signal.7.html – Richard Chambers Nov 07 '12 at 12:43

2 Answers2

5

It is guaranteed that precisely one thread receives the signal, but it is also unspecified which thread that is.

The proper thing to do is to block signals on all threads but one, so that that thread alone deals with signal handling; or on Linux specifically block threads everywhere and set up a signalfd to catch signals — that way, you don't introduce any asynchronousity and signals become just one more file descriptor to read from.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

Since you asked about POSIX, from man signal(7)

POSIX.1 distinguishes the notions of signals that are directed to the process as a whole and signals that are directed to individual threads. According to POSIX.1, a process-directed signal (sent using kill(2), for example) should be handled by a single, arbitrarily selected thread within the process.

So in short, it means a random thread will be chosen to handle the signal.

iabdalkader
  • 17,009
  • 4
  • 47
  • 74