Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 135 ยท Advanced C

Signals and Signal Handling

Learn signal handling in C - SIGINT, SIGTERM, SIGALRM and more, signal() vs sigaction, raise and kill, async-signal-safe handlers and graceful shutdown.

When you press Ctrl+C in a terminal, the program stops. Nothing in its code asked for that: the operating system sent it a signal, a small numbered notification that interrupts whatever the program is doing. Signals report many events: the user wants to quit (SIGINT), the system is shutting down (SIGTERM), a timer ran out (SIGALRM), the program touched memory it doesn't own (SIGSEGV), or a child process finished (SIGCHLD).

Every signal has a default action, usually "terminate the process". A program can replace that action with a function of its own, a signal handler, to clean up, save work, or simply ignore the event. This lesson shows how to do that correctly. Signal handlers run at unpredictable moments, so they follow stricter rules than any other code you write in C, and most signal bugs come from breaking those rules.

Standard C defines only a tiny part of this: <signal.h> with signal(), raise() and six signal names. Everything else here (sigaction, kill, alarm, blocking signals) is POSIX, available on Linux, macOS and other Unix systems but not on Windows. The examples define _POSIX_C_SOURCE because our compiler runs in strict -std=c23 mode, which hides POSIX functions unless you ask for them.

The signals you'll meet

Signal Typical cause Default action Standard
SIGINT Ctrl+C in the terminal Terminate C
SIGTERM A polite "please exit" (kill, service managers, docker stop) Terminate C
SIGABRT abort(), a failed assert Terminate + core dump C
SIGSEGV Invalid memory access Terminate + core dump C
SIGFPE Arithmetic error, such as integer division by zero Terminate + core dump C
SIGILL Illegal machine instruction Terminate + core dump C
SIGKILL kill -9: forced termination Terminate (can't be caught) POSIX
SIGALRM A timer set with alarm() expired Terminate POSIX
SIGHUP The terminal closed; daemons use it for "reload config" Terminate POSIX
SIGPIPE Writing to a pipe or socket nobody reads Terminate POSIX
SIGCHLD A child process stopped or exited Ignore POSIX
SIGUSR1, SIGUSR2 Free for your own use Terminate POSIX

SIGKILL and SIGSTOP are special: no program can catch, block or ignore them. That's what makes kill -9 a last resort that always works, and also why it gives the program no chance to clean up.

What happens when nobody handles a signal

The function raise(sig) sends a signal to the program itself. It's the easiest way to experiment, because you can trigger any signal from ordinary code. Here the program raises SIGTERM without installing a handler, so the default action applies:

C A signal with its default action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output panel shows only Starting up, followed by a note that the program was stopped by SIGTERM. The second line was printed with printf but never appeared: when a program's output goes to a pipe or a file (as it does here), stdout is fully buffered, and a process killed by a signal never flushes its buffers. That's a practical reason to handle termination signals in long-running programs: without a handler, unsaved data in buffers is simply lost. File Handling has more on stdio buffering.

Catching a signal with signal()

To handle a signal, write a function that takes the signal number and returns nothing, then pass it to signal():

C
void handler(int signum);
void (*signal(int signum, void (*handler)(int)))(int);   // returns the previous handler

The second argument can also be one of two special values: SIG_IGN (ignore the signal) or SIG_DFL (restore the default action). On failure signal() returns SIG_ERR.

C Handling SIGINT twice with signal()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first SIGINT is caught and counted. The second one kills the program: the output ends with a note that it was stopped by SIGINT. This isn't a bug in the example. It's the historical System V behavior of signal(): the handler is reset to SIG_DFL each time it runs, so it fires only once. BSD systems keep the handler installed instead. The C standard allows both, and glibc picks one depending on the compiler mode: strict -std=c23 gets the System V version, while the default GNU mode gets the BSD one. Code that has to behave the same everywhere shouldn't rely on signal() for anything beyond SIG_IGN and SIG_DFL. The POSIX function sigaction, covered below, removes the guesswork.

Ignoring a signal is a legitimate, common use: network servers call signal(SIGPIPE, SIG_IGN) so that writing to a closed connection returns an error (EPIPE) instead of killing the whole server. You'll see that again in Network Programming with Sockets.

What a handler is allowed to do

A signal can arrive between any two machine instructions. Imagine main is halfway through malloc, holding the allocator's internal lock and with its free lists half updated. If the handler now calls printf, which itself may call malloc, the program can deadlock or corrupt the heap. For this reason a handler may only call async-signal-safe functions, a list fixed by POSIX. A few you'll actually use:

Safe in a handler Not safe in a handler
write, read, open, close printf, fprintf, puts and all of stdio
_exit, _Exit exit (it runs atexit handlers and flushes stdio)
signal, sigaction, raise, kill malloc, free, realloc
alarm, getpid, sigprocmask pthread_mutex_lock, most of the C library

The data side has a rule too. The only object type that C guarantees can be written in a handler and read in normal code is volatile sig_atomic_t. sig_atomic_t is an integer type that is read and written in one indivisible step, and volatile stops the compiler from caching the value in a register (without it, a loop like while (!stop) { ... } might never see the change). In practice this gives you the standard handler pattern: set a flag, return, and let normal code do the real work.

One more detail: a handler that calls a function which sets errno (even write) can overwrite an errno value that main was about to inspect. Save it at the start of the handler and restore it before returning.

C A handler that only sets a flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The handler does two things only: it records which signal arrived and writes a fixed message with write. All formatting happens in main, which may use printf freely. Notice the fflush(stdout) before each raise: write bypasses the stdio buffer, so without the flush the handler's messages would appear before earlier printf lines. This is the same mismatch you'll meet in Low-Level I/O with System Calls.

Installing handlers with sigaction

sigaction is the POSIX replacement for signal(). It takes a struct sigaction describing exactly what you want, and its behavior is the same on every POSIX system. The example above already used it; these are the fields that matter:

  • sa_handler: the handler function, or SIG_IGN/SIG_DFL.
  • sa_mask: extra signals to block while the handler runs (the signal being handled is blocked automatically). Always initialize it, usually with sigemptyset.
  • sa_flags: options. SA_RESTART makes interrupted calls like read restart automatically instead of failing with EINTR; SA_RESETHAND gives the one-shot behavior on purpose; SA_SIGINFO selects a three-argument handler, sa_sigaction, that receives a siginfo_t with details such as the sender's process ID.

A handler installed with sigaction and no SA_RESETHAND stays installed, which is why the loop above caught SIGUSR1 twice. Use memset (or = {0}) on the struct first so no field is left with garbage, and check the return value in real code: it's -1 with errno set on failure.

Timers with alarm()

alarm(seconds) asks the system to send SIGALRM to the process after that many seconds; alarm(0) cancels a pending alarm. Combined with a flag, it puts a time limit on work that might otherwise run too long:

C A time limit with alarm()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The loop checks time_is_up on every round, and the handler flips it once a second has passed. (The exact number of steps depends on the machine, so the program only reports a rough result.) When a signal arrives during nanosleep, the call returns early with EINTR; the loop simply checks the flag and stops. alarm has one-second resolution and there's only one alarm per process. For finer or repeating timers, POSIX has setitimer and timer_create.

Blocking signals for a moment

Sometimes a signal must not interrupt a particular stretch of code, for example while you update several related variables. Blocking a signal with sigprocmask doesn't discard it: the signal becomes pending and is delivered as soon as you unblock it.

C A blocked signal waits until it is unblocked

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

While SIGINT is blocked, the handler doesn't run and sigpending reports the signal as waiting. Restoring the old mask delivers it immediately. Note that several instances of the same standard signal arriving while blocked collapse into one: signals are not a queue, and you shouldn't use them to count events precisely.

Graceful shutdown

The most common reason to handle signals is to stop cleanly. A service manager sends SIGTERM, the user presses Ctrl+C (SIGINT), and the program should finish the job in progress, save its state, close files and exit with a normal status. The handler only sets a flag; the main loop checks it between units of work. In this simulation the program sends itself SIGTERM during the third job with kill(getpid(), SIGTERM), exactly what another process would do:

C Finishing the current job, then shutting down

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Job 3 is interrupted by the signal but still runs to completion, because the handler only records the request. The loop then sees the flag and stops before job 4, the cleanup code runs, and main returns 0. Compare that with the first example in this lesson, where the same signal destroyed buffered output. If the cleanup could hang, many programs restore the default action after the first request, so a second Ctrl+C kills the program immediately.

Sending signals from outside

From a shell, the kill command sends any signal to a process ID, and kill -l lists them. Despite the name, it doesn't have to kill anything:

Terminal
kill -TERM 4242        # polite request to exit (the default signal)
kill -USR1 4242        # a custom meaning, such as "rotate the log file"
kill -9 4242           # SIGKILL: cannot be caught, no cleanup

In C, kill(pid, signum) does the same; it returns 0 on success, or -1 with errno set to ESRCH (no such process) or EPERM (not allowed). kill(pid, 0) sends nothing but checks that the process exists and you may signal it. raise(sig) is the portable standard C way to signal yourself.

SIGSEGV and SIGFPE: report, don't recover

SIGSEGV, SIGFPE, SIGILL and SIGBUS mean the program has hit a bug. When a handler for one of them simply returns, the CPU re-executes the faulting instruction, which faults again, forever. And the faults themselves usually come from undefined behavior, such as dereferencing a null pointer or dividing an integer by zero, after which nothing about the program's state can be trusted.

The only reasonable things a handler for these can do are to write a short message with write and end the process with _exit (or restore SIG_DFL and raise the signal again, so a core dump is still produced for the debugger). Crash reporters work this way. Don't try to "catch" a segmentation fault the way you'd catch an exception in another language.

Signals and threads

In a multithreaded program, a signal sent to the process is delivered to any one thread that doesn't block it, so handlers become even harder to reason about. The usual design is to block the signals in main before creating any threads (new threads inherit the mask), then dedicate one thread to waiting for them synchronously with sigwait. That thread receives the signal as an ordinary return value and can use mutexes and printf freely, because it isn't inside a handler:

C
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
pthread_sigmask(SIG_BLOCK, &set, NULL);   // before pthread_create

/* ... start worker threads ... */

int signum;
sigwait(&set, &signum);                    // in the signal-handling thread
printf("Got %s, stopping workers\n", strsignal(signum));

Linux also offers signalfd, which turns signals into data you read from a file descriptor, so a server can handle them in the same event loop as its sockets.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type should a flag shared between a signal handler and main have?

    sig_atomic_t is read and written in one indivisible step, and volatile makes every access go to memory, so main sees the handler's change. It's the only type the C standard guarantees for this. (Lock-free C11 atomics also work in practice.)
  2. 2. Why shouldn't a signal handler call printf?

    printf is not async-signal-safe. Use write for a fixed message, or set a flag and print from normal code.
  3. 3. A program built with -std=c23 calls signal(SIGINT, handler) and then raise(SIGINT) twice. What happens with glibc?

    In strict ISO mode glibc's signal() has System V semantics and resets the handler to SIG_DFL when it runs. sigaction without SA_RESETHAND keeps the handler installed.
  4. 4. SIGINT is blocked with sigprocmask, then raised. What happens?

    Blocking delays delivery; it doesn't discard the signal. sigpending shows it as pending until the mask changes.
  5. 5. Which signal can a program never catch, block or ignore?

    SIGKILL (and SIGSTOP) always take their default action. That's why kill -9 always works and why it gives the program no chance to clean up.

Summary

  • A signal is an asynchronous notification from the system, another process or the program itself. Most default actions terminate the process, and a killed process doesn't flush its stdio buffers.
  • Standard C offers signal(), raise() and six signals; POSIX adds sigaction, kill, alarm, sigprocmask and many more signals.
  • signal()'s behavior after a handler runs differs between systems; use sigaction (with sa_mask initialized) for handlers, and signal() only for SIG_IGN/SIG_DFL.
  • Handlers may only call async-signal-safe functions such as write and _exit, and should save and restore errno.
  • Share state through volatile sig_atomic_t flags: the handler sets the flag, normal code does the work.
  • alarm gives simple timeouts; blocked signals stay pending until unblocked; SIGKILL and SIGSTOP can't be handled.
  • For graceful shutdown, handle SIGTERM and SIGINT with a flag and let the main loop finish, clean up and exit normally.
  • Never try to resume after SIGSEGV or SIGFPE; in threaded programs, block signals and wait for them with sigwait in one thread.

Next: Network Programming with Sockets