sig_atomic_t


A common design pattern with signal handlers is for the signal handler to set a global flag, and for main program to periodically check if this flag is set, and if so, perform some action.

There are two issues that arise with this pattern. First, a compiler examining the code for the main program may see that the main program never updates the flag, and thus optimize the code such that the compiled code does not reflect the fact that the handler may update the flag. For instance, the compiler may store the flag in a register, and thus not emit code to re-load the flag's value from memory. To inform the compiler not to optimize accesses to the flag variable, we declare it as a volatile.

The second issue is that accesses to the flag variable may be involve multiple instructions, and the kernel may deliver the signal in between these instructions. For instance, the main program may start reading the flag value of zero when the signal handler sets it to zero -- it's unclear whether the main program will see the flag as set (a value of 1) or unset (0). To handle this situation, we use the sig_atomic_t type for the flag: the C standard guarantees that loads and stores of a value of this type are atomic.

sig_atomic.c