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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With