Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 171 ยท Errors and Debugging

Signal Handling

Handle signals in C++ with <csignal> - std::signal and std::raise, what a handler may safely do, sig_atomic_t and atomic flags, graceful shutdown and threads.

Exceptions report errors that your own code detects. Signals are different: they come from outside the normal flow of the program. The operating system sends one when the user presses Ctrl+C (SIGINT), when a service manager asks the program to stop (SIGTERM), or when the program does something fatal, such as touching memory it doesn't own (SIGSEGV). A signal interrupts the program wherever it happens to be, runs a handler if one is installed, and otherwise performs a default action, which for most signals is to kill the process on the spot.

That "on the spot" is the part that matters for C++. A process killed by a signal doesn't unwind the stack, so no destructors run: files aren't flushed, temporary files aren't deleted, and transactions aren't finished. Handling SIGINT and SIGTERM lets a program shut down gracefully instead. But a handler runs at an unpredictable moment, in the middle of any other code, so it may do almost nothing except set a flag. This lesson shows the standard <csignal> tools, the rules for safe handlers, the shutdown pattern every server uses, and how signals interact with threads.

The standard signals

<csignal> (the C++ version of C's <signal.h>) defines six signals that every platform supports:

Signal Meaning Typical cause
SIGINT Interactive interrupt Ctrl+C in a terminal
SIGTERM Termination request kill, docker stop, a service manager, system shutdown
SIGABRT Abnormal termination std::abort(), a failed assert, an uncaught exception
SIGSEGV Invalid memory access Null or dangling pointer, buffer overrun
SIGFPE Arithmetic error Integer division by zero
SIGILL Illegal instruction Corrupted code, or a CPU feature the machine lacks

POSIX systems (Linux, macOS) have many more, such as SIGHUP, SIGPIPE, SIGALRM, SIGUSR1 and SIGKILL (which can never be caught). Windows supports only the six above, plus SIGBREAK for Ctrl+Break. The C lesson Signals and Signal Handling covers the POSIX-only tools like sigaction, alarm and blocking signals in depth.

The default action: no stack unwinding

std::raise(sig) sends a signal to the current program. It's the easiest way to watch signals at work. Here, nothing handles SIGTERM, so the default action applies:

C++ A signal kills the program without running destructors

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 std::cin or std::getline), it gets the next line from this box.

The output stops after Working..., followed by a note that the program was stopped by SIGTERM. The destructor never ran, and the unflushed line is gone too: when output goes to a pipe or file, as it does here, it's buffered, and a killed process never flushes its buffers. That's the C++ argument for handling termination signals: RAII only cleans up when the program leaves scopes normally.

Installing a handler with std::signal

std::signal(sig, handler) installs a function that takes the signal number and returns nothing. Instead of a function you can pass SIG_IGN (ignore the signal) or SIG_DFL (restore the default). It returns the previous handler, or SIG_ERR on failure. A lambda without captures converts to a plain function pointer, so it works as a handler too.

C++ Catching SIGINT with std::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 std::cin or std::getline), it gets the next line from this box.

The handler stores the signal number (2 for SIGINT on Linux), the program continues, and once the signal is ignored it has no effect at all. Two portability notes. First, the standard allows a platform to reset the handler to SIG_DFL each time it runs: Windows does, and glibc does in strict C mode, while glibc in C++ mode keeps it installed. Don't depend on the handler staying installed for a second signal; on POSIX systems sigaction gives precise control. Second, extern "C" is the traditional way to declare a handler, because the C library calls it. With GCC, Clang and MSVC an ordinary C++ function or a captureless lambda works the same.

What a handler is allowed to do

A signal can arrive while the main program is in the middle of anything: inside operator new with the allocator's lock held, halfway through writing to std::cout, or while holding a std::mutex. If the handler then calls the same code, the program can deadlock or corrupt memory. So the C++ standard allows only signal-safe operations in a handler. Anything else is undefined behavior:

Allowed in a handler Not allowed in a handler
Writing to a volatile std::sig_atomic_t std::cout, std::println, printf
Lock-free std::atomic operations (is_always_lock_free) new, delete, std::string, std::vector growth
std::signal, std::abort, std::_Exit, std::quick_exit std::mutex, condition variables, most of the library
POSIX async-signal-safe calls like write (on POSIX systems) Throwing an exception out of the handler

In practice this leaves one pattern: the handler sets a flag, and normal code checks the flag and does the real work. Two kinds of flag are safe. volatile std::sig_atomic_t is the classic C type, an integer that can be written in one step, with volatile ensuring the main loop rereads it. Since C++17, a lock-free std::atomic is also allowed, and it's the better choice when other threads read the flag too, because volatile gives no thread safety. Check lock-freedom with static_assert, as the next example does.

Graceful shutdown

Here is the shape of almost every long-running C++ program that handles termination: install handlers for SIGINT and SIGTERM, run the main loop until the flag is set, then leave main normally so every destructor runs. The example sends itself SIGTERM during the third job, which is what docker stop or systemctl stop would do from outside:

C++ Finishing the current job, then shutting down cleanly

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 std::cin or std::getline), it gets the next line from this box.

Job 3 still finishes and is saved, because the handler only flipped the flag. The loop then stops before job 4, main returns, and the Database destructor commits and closes. Compare this with the first example, where the same signal skipped every destructor. Many programs also restore SIG_DFL after the first request, so pressing Ctrl+C a second time kills a program whose cleanup is stuck.

Don't be tempted to call std::exit from the handler instead. It isn't signal-safe, and even outside a handler it doesn't run destructors of local variables. std::quick_exit is signal-safe, but it skips almost all cleanup, so it's for emergencies only. Throwing an exception from a handler is undefined behavior too.

Signals and threads

In a multithreaded program, a signal sent to the process is delivered to some thread, and you don't control which. The flag pattern still works if the flag is a lock-free std::atomic, but there is a cleaner design on POSIX systems: block the signals in main before creating any threads (new threads inherit the blocked set), then dedicate one thread to waiting for them with sigwait. That thread isn't running a handler; it receives the signal as an ordinary return value, so it may use any library function, including std::jthread's stop mechanism from Threads:

C++ A signal-waiting thread stops the workers

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 std::cin or std::getline), it gets the next line from this box.

The workers know nothing about signals; they only watch their std::stop_token. The signal thread turns SIGTERM into a stop request, and joining the threads finishes the shutdown. (The exact number of jobs depends on timing, so the program only reports that some were done.) sigwait and pthread_sigmask are POSIX, not standard C++; on Windows, console programs receive Ctrl+C through SetConsoleCtrlHandler, which already runs the callback on a separate thread.

Fatal signals: report, then die

SIGSEGV, SIGFPE and SIGILL mean the program has a bug, usually undefined behavior such as a null pointer dereference or an integer division by zero. Don't try to continue after one: if a handler for a real fault returns, the faulting instruction runs again and faults again, and the program's state can't be trusted anyway. What a handler can usefully do is leave a last message and then let the default action happen, so the crash is still reported (and a core dump is still produced for the debugger). Crash reporters work like this:

C++ A last-words handler for fatal signals

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 std::cin or std::getline), it gets the next line from this box.

The handler's message appears on stderr, and the program then dies with the normal SIGFPE crash. The example raises the signal deliberately, because a real division by zero would be undefined behavior and the compiler might not even produce a fault. To find such bugs, sanitizers are far more useful than handlers; see Assertions and Debugging.

Signals and exceptions don't mix in the other direction either: a failed assert and an uncaught exception both end in std::abort(), which raises SIGABRT. To customize what happens on an uncaught exception, use std::set_terminate rather than a SIGABRT handler (see Exceptions).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A program with a local RAII object receives SIGTERM and has no handler. What happens to the object's destructor?

    The default action for SIGTERM terminates the process immediately. No destructors run and unflushed buffers are lost, which is why servers handle SIGTERM.
  2. 2. Which of these is safe to do inside a signal handler?

    Lock-free atomic operations and writes to volatile std::sig_atomic_t are signal-safe. Output, allocation and mutexes can deadlock or corrupt state if the signal interrupted the same code.
  3. 3. After std::signal(SIGINT, SIG_IGN); std::raise(SIGINT);, what happens?

    SIG_IGN tells the system to discard the signal. SIG_DFL would restore the default action, which terminates the program.
  4. 4. Why is a separate thread calling sigwait often better than a handler in a multithreaded program?

    With the signals blocked in all threads, only the sigwait call receives them, outside of any handler. SIGKILL can never be caught.
  5. 5. A SIGSEGV handler logs a message with write() and then returns. What happens next?

    Returning from a handler for a real fault re-executes the faulting instruction. Restore SIG_DFL and re-raise the signal (or call _Exit) instead.

Summary

  • Signals are asynchronous notifications such as SIGINT (Ctrl+C), SIGTERM (stop request), SIGABRT, SIGSEGV and SIGFPE; <csignal> provides std::signal, std::raise and std::sig_atomic_t.
  • Most default actions kill the process without stack unwinding: destructors don't run and buffered output is lost.
  • std::signal(sig, handler) installs a handler; SIG_IGN ignores a signal and SIG_DFL restores the default. Whether the handler stays installed after it runs is platform-specific.
  • Handlers may only do signal-safe things: write a volatile std::sig_atomic_t or a lock-free std::atomic, and call a few functions such as std::_Exit. No output, allocation, locks or exceptions.
  • Graceful shutdown: the handler sets a flag, the main loop finishes the current work and leaves main normally, so RAII cleans up.
  • With threads on POSIX, block the signals before starting threads and receive them in one thread with sigwait, then stop the workers with std::stop_source.
  • After SIGSEGV/SIGFPE, only leave a message, restore SIG_DFL and re-raise; find the bug with sanitizers.

Next: Assertions and Debugging