Signal Handling in C
Signals are the OS tapping your program's shoulder: SIGINT (Ctrl-C), SIGTERM (polite shutdown request), SIGSEGV/SIGFPE (crashes you usually shouldn't catch). signal() or sigaction() installs a handler that runs asynchronously — which restricts handlers to async-signal-safe work: set a volatile sig_atomic_t flag and return, letting the main loop notice and shut down cleanly.
printf, malloc, and most library calls are forbidden inside handlers (they may re-enter broken state). The robust pattern is minimal handlers plus main-loop polling — flags in, full cleanup out here.
Install handlers
signal(SIGINT, on_int); routes Ctrl-C to your function; sigaction() offers finer control (masks, flags, info).
Flags only inside
static volatile sig_atomic_t stop = 0; set to 1 in the handler — the only safely sharable type, written atomically.
Nothing fancy in handlers
No printf, no malloc, no locks inside — async execution can interrupt those very functions mid-call.
Poll in main loop
while (!stop) { work(); } notices the flag at a safe point and performs full, ordinary cleanup.
#include <stdio.h>#include <signal.h> static volatile sig_atomic_t stop = 0; void on_int(int sig) { (void)sig; stop = 1;} int main(void) { signal(SIGINT, on_int); printf("armed, flag=%d\n", (int)stop); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.