Learn C
#include "advanced/signal_handling.h"

Signal Handling in C

#concept

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.

#how it works
1

Install handlers

signal(SIGINT, on_int); routes Ctrl-C to your function; sigaction() offers finer control (masks, flags, info).

2

Flags only inside

static volatile sig_atomic_t stop = 0; set to 1 in the handler — the only safely sharable type, written atomically.

3

Nothing fancy in handlers

No printf, no malloc, no locks inside — async execution can interrupt those very functions mid-call.

4

Poll in main loop

while (!stop) { work(); } notices the flag at a safe point and performs full, ordinary cleanup.

#example
#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;
}
Output
armed, flag=0
1stop starts 0; the handler does exactly one safe thing — set the flag.
2Installing the handler arms Ctrl-C handling; nothing has arrived yet, so flag reads 0.
3armed, flag=0 prints — a real loop would now poll stop until a signal flips it.
#use cases
Graceful Ctrl-C shutdown (flush, close, save) via flag polling
SIGTERM handling in daemons and containers
Ignoring SIGPIPE in network servers that outlive clients
Keeping handlers to flag-sets and main loops to real work

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.