Pepedou
Pepedou

Reputation: 829

Are all threads halted when one of them receives a signal and none of them block it?

I'm running a multithreaded application written in C on Linux.

To stop execution I send SIGINT and from the signal handler call a number of cleanup routines and, finally, call exit(0).

Are the other threads still running or may run (context switch) while the handler executes the cleanup routines?

Upvotes: 10

Views: 2019

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215257

Handling a signal does not cause the suspension of other threads during execution of the signal handler. Moreover, it's generally not safe to call most functions you would need for cleanup (including even exit!) from a signal handler unless you can ensure that it does not interrupt an async-signal-unsafe function.

What you should do is simply store the fact that SIGINT was received in some async-signal-safe manner and have the program act on that condition as part of its normal flow of execution, outside the signal handler. Then you can properly synchronize with other threads (using mutexes, condition variables, etc.) to achieve a proper, safe shutdown. The ideal method is not to even install a signal handler, but instead block all signals and have a dedicated signal-handling thread calling sigwaitinfo in a loop to accept signals.

Upvotes: 9

Kerrek SB
Kerrek SB

Reputation: 477070

Yes, a signal is delivered to one thread, chosen in an unspecified way. Only threads that aren't blocking the signal are considered, though; if all threads block the signal, it remains queued up until one thread unblocks it.

(So if you make all threads block the signal, you can use the signal as a deterministic, inter-process synchronization mechanism, e.g. using sigwait.)

Upvotes: 4

Related Questions