...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <signal.h>
sig_atomic_t interrupted; /* Bug: not declared volatile */
void sigint_handler(int signum) {
interrupted = 1; /* Assignment may not be visible in main() */
}
int main(void) {
signal(SIGINT, sigint_handler);
while (!interrupted) { /* Loop may never terminate */
/* Do something... */
}
return 0;
}
|
Compliant Solution
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <signal.h>
volatile sig_atomic_t interrupted;
void sigint_handler(int signum) {
interrupted = 1;
}
int main(void) {
signal(SIGINT, sigint_handler);
while (!interrupted) {
/* Do something... */
}
return 0;
}
|
The sig_atomic_t type is the integer type of an object that can be accessed as an atomic entity even in the presence of asynchronous interrupts. The type of sig_atomic_t is implementation-defined, though it provides some guarantees. Integer values ranging from SIG_ATOMIC_MIN through SIG_ATOMIC_MAX may be safely stored to a variable of the type. In addition, when sig_atomic_t is a signed integer type, SIG_ATOMIC_MIN must be no greater than -127 and SIG_ATOMIC_MAX no less than 127. Otherwise, SIG_ATOMIC_MIN must be 0 and SIG_ATOMIC_MAX must be no less than 255. The macros SIG_ATOMIC_MIN and SIG_ATOMIC_MAX are defined in the header <stdint.h>.
...