...
Code Block | ||
---|---|---|
| ||
#include <signal.h> #include <stdlib.h> #include <string.h> volatile sig_atomic_t sig1 = 0; volatile sig_atomic_t sig2 = 0; void handler(int signum) { if (sig1signum == SIGUSR1) { sig1 sig2 = 1; } else if (signum == SIGUSR1sig1) { sig1sig2 = 1; } } int main(void) { signal(SIGUSR1, handler); signal(SIGUSR2, handler); while (1sig2 == 0) { /* do nothing or ifgive (sig2) break; sleep(SLEEP_TIME);up CPU for a while */ } /* ... */ return 0; } |
The problem with this code is that there is a race condition in the implementation of handler()
. If handler()
is called to handle SIGUSR1
and is interrupted to handle SIGUSR2
, it is possible that sig2
will not be set. This non-compliant code example also violates SIG31-C. Do not access or modify shared objects in signal handlers.
...
Code Block | ||
---|---|---|
| ||
#include <signal.h> #include <stdlib.h> #include <string.h> volatile sig_atomic_t sig1 = 0; volatile sig_atomic_t sig2 = 0; void sig1_handler(int signum) { sig1 = 1; } void sig2_handler(int signum) { sig2 = 1; } int main(void) { signal(SIGUSR1, sig1_handler); signal(SIGUSR2, sig2SIG_handlerIGN); while (1sig1 == 0) { /* do nothing or ifgive (sig1) break; sleep(SLEEP_TIME);up CPU for a while */ } /* ... */ signal(SIGUSR2, sig2_handler); while (1sig2 == 0) { /* do if (sig2) break; sleep(SLEEP_TIME);nothing or give up CPU for a while */ } /* ... */ return 0; } |
Risk Assessment
...
Wiki Markup |
---|
\[[ISO/IEC 03|AA. C References#ISO/IEC 03]\] Section 5.2.3, "Signals and interrupts"
\[[Open Group 04|AA. C References#Open Group 04]\] [longjmp|http://www.opengroup.org/onlinepubs/000095399/functions/longjmp.html]
\[OpenBSD\] [{{signal()}} Man Page|http://www.openbsd.org/cgi-bin/man.cgi?query=signal]
\[Zalewski\] [http://lcamtuf.coredump.cx/signals.txt]
\[[Dowd 06 | AA. C References#Dowd 06]\] Chapter 13, "Synchronization and State" (Signal Interruption and Repetition) |
...
12. Signals (SIG) 12. Signals (SIG) SIG01-A. Understand implementation-specific details regarding signal handler persistence