...
| Code Block |
|---|
#include <stdio.h>
#include <signal.h>
volatile sig_atomic_t e_flag = 0;
void handler(int signum) {
e_flag = 1;
}
int main(void) {
if (signal(SIGINT, handler);) == SIG_ERR) {
/* handle error */
}
while (!e_flag) {}
puts("Escaped from first while ()");
e_flag = 0;
while (!e_flag) {}
puts("Escaped from second while ()");
return 0;
}
|
...
| Code Block | ||
|---|---|---|
| ||
void handler(int signum) {
if (signal(signum, handler);) == SIG_ERR) {
/* handle error */
}
/* handle signal */
}
|
Unfortunately, this solution still contains a race window, starting when the host environment resets the signal and ending when the handler calls signal(). During that time, a second signal sent to the program will trigger the default signal behavior, defeating the persistent behavior (see SIG34-C. Do not call signal() from within interruptible signal handlers).
...
| Code Block | ||
|---|---|---|
| ||
void handler(int signum) {
#ifndef WINDOWS
if (signal(signum, SIG_DFL);) == SIG_ERR) {
/* handler error */
}
#endif
/* handle signal */
}
|
...