...
This noncompliant code example fails to persist the signal handler on Windows platforms and on those UNIX systems where handlers are not persistent by default.
| Code Block | ||||
|---|---|---|---|---|
| ||||
void handler(int signum) {
/* Handle signal */
}
|
...
A common approach to create persistent signal handlers is to call signal() from within the handler itself, consequently, unresetting the reset signal.
| Code Block | ||||
|---|---|---|---|---|
| ||||
void handler(int signum) {
if (signal(signum, handler) == SIG_ERR) {
/* Handle error */
}
/* Handle signal */
}
|
...
The POSIX sigaction() function assigns handlers to signals in a manner similar to the C99 signal() function but also allows signal handler persistence to be controlled via the SA_RESETHAND flag. (Leaving the flag clear makes the handler persistent.)
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* Equivalent to signal(SIGUSR1, handler) but makes
* signal persistent */
struct sigaction act;
act.sa_handler = handler;
act.sa_flags = 0;
if (sigemptyset(&act.sa_mask) != 0) {
/* Handle error */
}
if (sigaction(SIGUSR1, &act, NULL) != 0) {
/* Handle error */
}
|
...
This noncompliant code example fails to reset the signal handler to its default behavior on systems where handlers are persistent by default.
| Code Block | ||||
|---|---|---|---|---|
| ||||
void handler(int signum) {
/* Handle signal */
}
|
...
A C99-compliant solution to reset the handler on a UNIX system is to rebind the signal to the default handler in the first line of the handler itself. Windows, however, automatically resets handlers to their default behavior.
| Code Block | ||||
|---|---|---|---|---|
| ||||
void handler(int signum) {
#ifndef WINDOWS
if (signal(signum, SIG_DFL) == SIG_ERR) {
/* Handler error */
}
#endif
/* Handle signal */
}
|
...
The POSIX sigaction() function assigns handlers to signals in a manner similar to the C99 signal() function but also allows signal handler persistence to be controlled via the SA_RESETHAND flag. (Setting the flag makes the handler nonpersistent.)
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* Equivalent to signal(SIGUSR1, handler) but makes
* signal nonpersistent */
struct sigaction act;
act.sa_handler = handler;
act.sa_flags = SA_RESETHAND;
if (sigemptyset(&act.sa_mask) != 0) {
/* Handle error */
}
if (sigaction(SIGUSR1, &act, NULL) != 0) {
/* Handle error */
}
|
...