0

The signal mask can be set on a per thread basis, but what about signal handles? If I call sigaction() before creating new threads with pthread_create(), will the new threads get the same signal handler? What if I use sigaction() after pthread_create(), will that change the entire process signal handlers or just the ones of the thread?

Kouros
  • 341
  • 5
  • 19

1 Answers1

2

There is only ONE signal handler per process. So threads are not relevant in any kind here. The signal handler is called in the thread context which receives the signal. Which thread receives the signal is not specified if multiple threads have not blocked the signal.

You have to take care if multiple threads waits in system calls. Also you have to take care with using timer actions and calls to sleep.

You may also find this answer helpful: POSIX threads and signals

Community
  • 1
  • 1
Klaus
  • 24,205
  • 7
  • 58
  • 113
  • Ok thank you for your answer. And are signals delivered asynchronous or deferred? `pthread_cancel()` can be tweeked, but what about `pthread_kill()`? I read that signal do use cancellation points, but they can interrupt even a system call. – Kouros Oct 07 '15 at 11:04
  • 1
    `The signal handler is called in its own context which is non of the threads one.` - No. According to [man signal(7)](http://man7.org/linux/man-pages/man7/signal.7.html): `A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.` – Tsyvarev Oct 07 '15 at 11:11
  • @Kouros Nearly every system call will be interrupted by signals. So you have to check for the return value. Normaly `EINTR` will be returned if a signal is handled. – Klaus Oct 07 '15 at 11:12
  • @Klaus, so signals are asynchronous by default, and the only way to make them deferred is by blocking them and then call `sigwait()`. @Tsyvarev, that was not my question – Kouros Oct 07 '15 at 11:17
  • sorry I did a mistake: I read that signals unlike `pthread_cancel()` do not use cancellation points, so they can interrupt library and even system calls (except if they are blocked with `pthread_sigmask()`). – Kouros Oct 07 '15 at 11:20
  • @Kouros: I mean that while this answer is mostly correct, it contains a statement which is not true. In my previous comment I just pointed to that statement. I know that question isn't concerned with signal handler execution. But having false statement in accepted answer may confuse futher SO readers. – Tsyvarev Oct 07 '15 at 11:39
  • @Tsyvarev: fixed it, Thanks! – Klaus Oct 07 '15 at 12:38