Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Only call asynchronous-safe functions within signal handlers.

Wiki Markup
According to the "Signals and Interrupts" section of the
C99 Rationale
 C Rationale \[[ISO/IEC 03|AA. C References#ISO/IEC 03]\]:

When a signal occurs, the normal flow of control of a program is interrupted. If a signal occurs that is being trapped by a signal handler, that handler is invoked. When it is finished, execution continues at the point at which the signal occurred. This arrangement could cause problems if the signal handler invokes a library function that was being executed at the time of the signal. Since library functions are not guaranteed to be reentrant, they should not be called from a signal handler that returns.

Implementation Details

...

Wiki Markup
Similarly, Section 7.14.1 paragraph 5 of C99 \[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] states that:

If the signal occurs other than as the result of calling the abort or raise function, the behavior is undefined if the signal handler refers to any object with static storage duration other than by assigning a value to an object declared as volatile sig_atomic_t, or the signal handler calls any function in the standard library other than the abort function, the _Exit function, or the signal function with the first argument equal to the signal number corresponding to the signal that caused the invocation of the handler.

Non-Compliant Code Example

...

The _Exit() function called from within the int_handler() signal handler causes immediate program termination, and is async-safe, whereas exit() may call cleanup routines first, and is consequently not async-safe.

Implementation Details

The OpenBSD signal() man page identifies functions that are asynchronous-signal safe. Applications may consequently invoke them, without restriction, from signal-catching functions.

Compliant Solution

Signal handlers should be as concise as possible, ideally unconditionally setting a flag and returning. They may also call the _Exit() function.

...