Issue
According to this answer, I can only longjmp()
out of a signal handler if it is not calling an async-signal-unsafe
function. Is there a reliable way to know, from inside the signal handler, if the process was executing a non async-signal-unsafe
function at the moment of the signal?
Solution
The obvious answer is that, after calling setjmp
, don't call any async-signal-unsafe functions. Then you know for sure.
Note that setjmp(3)
(Linux) has a slightly more specific definition for when the Undefined Behaviour occurs, and offers two ways to avoid it:
POSIX.1-2008 Technical Corrigendum 2 adds longjmp() and siglongjmp() to the list of async-signal-safe functions. However, the standard recommends avoiding the use of these functions from signal handlers and goes on to point out that if these functions are called from a signal handler that interrupted a call to a non-async-signal-safe function (or some equivalent, such as the steps equivalent to exit(3) that occur upon a return from the initial call to main()), the behavior is undefined if the program subsequently makes a call to a non-async-signal-safe function. The only way of avoiding undefined behavior is to ensure one of the following:
After long jumping from the signal handler, the program does not call any non-async-signal-safe functions and does not return from the initial call to main().
Any signal whose handler performs a long jump must be blocked during every call to a non-async-signal-safe function and no non-async-signal-safe functions are called after returning from the initial call to main().
Emphasis is mine, and highlights that UB only occurs if you call another async-signal-unsafe (non-async-signal-safe) function after jumping, which differs slightly, but significantly, from the description you read in the other answer.
This is described even more succinctly in signal-safety(7)
:
If a signal handler interrupts the execution of an unsafe function, and the handler terminates via a call to longjmp(3) or siglongjmp(3) and the program subsequently calls an unsafe function, then the behavior of the program is undefined.
Answered By - Oka Answer Checked By - Mildred Charles (WPSolving Admin)