Reputation: 21510
Is there a way I can call non async safe functions from within a signal handler? Or is this impossible?
I am not looking for setting a flag from within the signal handler and then print something in my "main code" but in this case the signal handlers will define the logical flow of my program in itself.
Upvotes: 3
Views: 2463
Reputation: 1
Is there a way I can call non async safe functions from within a signal handler? Or is this impossible?
No. Not safely. Doing so results in undefined behavior - most likely deadlocks, but other things can happen, too.
The reason any function call is labeled as "async signal safe" is for the very purpose of marking it as safe to call from within a signal handler.
From the signal(7)
Linux man page:
Async-signal-safe functions
A signal handler function must be very careful, since processing elsewhere may be interrupted at some arbitrary point in the execution of the program. POSIX has the concept of "safe function". If a signal interrupts the execution of an unsafe function, and handler calls an unsafe function, then the behavior of the program is undefined.
POSIX.1-2004 (also known as POSIX.1-2001 Technical Corrigendum 2) requires an implementation to guarantee that the following functions can be safely called inside a signal handler:
...
If the function call is not listed, it's not safe to call it from within a signal handler.
Upvotes: 4
Reputation: 3819
Technically you can call or write any function(s) inside the signal handler there is nothing preventing you from doing it.
The reason why its discouraged is that, when a signal handler is handling your operation, there could be another signal raised which could make the signal handler jump to the higher priority signal handler.
This kind of leads to race and hard to debug problems as we are not aware of the ordering of the handling of signals.
Thats the reason why the signal handlers are supposed to be light to avoid hard to debug race conditions and usually we set flags to indicate a signal has been raised and handle it in the main or another thread that reads these flags.
Upvotes: 3