capypad
0 day streak
c / expert
Snippet

Volatile and Signal Safety

The 'volatile' qualifier prevents the compiler from caching a variable's value in a register, forcing it to read from memory every time. 'sig_atomic_t' is a type that can be accessed as an atomic entity even in the presence of asynchronous interrupts. Together, they are essential for variables shared between the main execution thread and signal handlers to prevent infinite loops or race conditions.

snippet.c
c
1
2
3
4
5
6
7
8
9
#include <signal.h>
 
volatile sig_atomic_t keep_running = 1;
 
void handle_sigint(int sig) {
keep_running = 0;
}
 
// In main: while(keep_running) { /* loop */ }
Breakdown
1
volatile sig_atomic_t
Ensures the value is always fetched from RAM and access is atomic relative to signals.
2
keep_running = 0;
Safe update within a signal handler because the type is sig_atomic_t.