...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <signal.h> void term_handler(int signum) { /* SIGTERM handling specific */ } void int_handler(int signum) { /* SIGINT handling specific */ /* Pass control to the term handler */ term_handler(SIGTERM); } int main(void) { if (signal(SIGTERM, term_handler) == SIG_ERR) { /* Handle error */ } if (signal(SIGINT, int_handler) == SIG_ERR) { /* Handle error */ } /* Program code */ if (raise(SIGINT) != 0) { /* Handle error */ } /* More code */ return EXIT_SUCCESS; } |
Noncompliant Code Example (POSIX)
The POSIX standard [IEEE Std 1003.1:2013] is contradictory regarding raise()
in signal handlers. It prohibits signal handlers installed using signal()
from calling the raise()
function if the signal occurs as the result of calling the raise()
, kill()
, pthread_kill()
, or sigqueue()
functions. However, it allows the raise()
function to be safely called within any signal handler. Consequently, it is not clear whether it is safe for POSIX applications to call raise()
in signal handlers installed using signal()
, but it is safe to call raise()
in signal handlers installed using sigaction()
.
In this noncompliant code example, the signal handlers are installed using signal()
, and raise()
is called inside the signal handler:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <signal.h>
void log_msg(int signum) {
/* Log error message */
}
void handler(int signum) {
/* Do some handling specific to SIGINT */
if (raise(SIGUSR1) != 0) {
/* Handle error */
}
}
int main(void) {
signal(SIGUSR1, log_msg);
signal(SIGINT, handler);
/* Program code */
if (raise(SIGINT) != 0) {
/* Handle error */
}
/* More code */
return 0;
}
|
Implementation Details
POSIX
The following table from the POSIX standard [IEEE Std 1003.1:2013] defines a set of functions that are asynchronous-signal-safe. Applications may invoke these functions, without restriction, from a signal handler.
...
All functions not listed in this table are considered to be unsafe with respect to signals. In the presence of signals, all POSIX functions behave as defined when called from or interrupted by a signal handler, with a single exception: when a signal interrupts an unsafe function and the signal handler calls an unsafe function, the behavior is undefined.Note that although raise()
is on the list of asynchronous-safe functions, it should not be called within a signal handler if the signal occurs as a result of the abort()
or raise()
function.
Subclause 7.14.1.1, paragraph 4, of the C Standard [ISO/IEC 9899:2011] states:
...