Table of Contents

<signal.h>

<signal.h> provides signal handling for asynchronous events: SIGINT (Ctrl+C), SIGTERM, SIGSEGV, etc. Register a handler with signal(SIGNUM, handler). Handlers run asynchronously and can only safely call async-signal-safe functions like write and _exit.

The standard pattern is to set a flag in the handler and check it in the main loop.

Example

This example catches SIGINT by setting a flag that the main loop polls.

// compile: gcc -o signalexample signalexample.c
// run: ./signalexample (press Ctrl+C)
// description: signal handler that sets a flag for clean shutdown
 
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
 
volatile sig_atomic_t stop = 0;
 
void handler(int sig) {
    stop = 1;
}
 
int main() {
    signal(SIGINT, handler);
    puts("running... press Ctrl+C to stop");
 
    while (!stop) {
        putchar('.');
        fflush(stdout);
        sleep(1);
    }
 
    puts("\nshutting down cleanly");
    return 0;
}