A signal handler is allowed to call signal()
, and if that fails, signal()
returns SIG_ERR
and sets errno
to a positive value. However, if the event that caused a signal was external (not as the result of the program calling abort()
or raise()
), the only functions the signal handler may call are _Exit()
or abort()
, or call signal()
on the signal currently being handled, and if signal()
fails, the value of errno
is indeterminate.
...
The compliant solution does not reference errno
, and does not return from the signal handler if the signal()
call fails.
...
POSIX is less restrictive than C99 about what applications can do in signal handlers. It has a long list of asynchronous-safe functions that can be called (see SIG30-C. Call only asynchronous-safe functions within signal handlers). Many of these functions set errno
on error. This can lead to a situation where a signal handler is executed in between a call to a failed function and the subsequent inspection of errno
, and consequently the value inspected is not the one set by that function but the one set by a function call in the signal handler. POSIX applications can avoid this problem by ensuring that signal handlers which that contain code that might alter errno
always save the value of errno
on entry and restore it before returning.
The signal handler in this non-compliant code example alters the value of errno
, and resultantly, as a result it could cause incorrect error handling if executed in between a failed function call and the subsequent inspection of errno
.
...