Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 694
Pepedou Avatar asked Jul 10 '15 00:07

Pepedou


1 Answers

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.

like image 157
R.. GitHub STOP HELPING ICE Avatar answered Sep 28 '22 07:09

R.. GitHub STOP HELPING ICE