CC Explainer
C · 5 · Systems C27 / 35 · 77%

Signals & setjmp

Asynchronous interrupts, and the very short list of things a handler may do.

Examples: SIGINT, sigaction, setjmp/longjmp

shortcuts: ← prev · → next · M mark
1

Installing a Handler

Prefer sigaction over signal — its semantics are portable.

Example
example
#include <signal.h>
static volatile sig_atomic_t g_stop = 0;

static void on_sigint(int sig) { (void)sig; g_stop = 1; }

struct sigaction sa = {0};
sa.sa_handler = on_sigint;
sigaction(SIGINT, &sa, NULL);

while (!g_stop) { do_work(); }   // graceful shutdown
2

Async-Signal-Safe Only

Inside a handler you may call almost nothing.

Common pitfalls
  • ✕printf, malloc and free are NOT async-signal-safe — calling them can deadlock.
  • ✕Only write(), _exit(), and the documented safe list are allowed.
  • ✕Set a volatile sig_atomic_t flag and do the real work in the main loop.
3

Common Signals

Know what each one means.

Complexity
SIGINTCtrl+Ccatchable
SIGTERMpolite killcatchable
SIGKILLhard killcannot be caught
SIGSEGVbad memory access
SIGPIPEwrite to closed socketoften ignored in servers
4

setjmp / longjmp

A non-local goto — C's closest thing to an exception.

Example
example
#include <setjmp.h>
static jmp_buf env;

if (setjmp(env) == 0) {
    risky();          // may longjmp back here
} else {
    puts("recovered");
}

void risky(void) { longjmp(env, 1); }
WATCH OUT
longjmp skips all cleanup — anything malloc'd between setjmp and longjmp leaks. Use sparingly.