c / expert
Snippet
Asynchronous Safety with sig_atomic_t
'sig_atomic_t' is an integer type that can be accessed as an atomic entity even in the presence of asynchronous interrupts (signals). Combined with 'volatile', it prevents the compiler from caching the variable in a register, ensuring the main loop sees the update made by the signal handler.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>#include <signal.h>#include <unistd.h>volatile sig_atomic_t keep_running = 1;void handle_sigint(int sig) {keep_running = 0;}int main() {signal(SIGINT, handle_sigint);printf("Running loop. Press Ctrl+C to stop...\n");while (keep_running) {// Simulate work}printf("Clean exit.\n");return 0;}
Breakdown
1
volatile sig_atomic_t keep_running
Guarantees that reads/writes are atomic relative to signals and bypasses compiler optimizations.
2
keep_running = 0;
Safe to execute inside a signal handler because the operation is guaranteed to be atomic.