A C++ daemon must flush its logs on SIGTERM; how do std::exit, std::quick_exit, std::abort and std::terminate differ in what they run?
answer
- four exits, four cleanup levels
- at_quick_exit, not atexit
- signal-safe functions
- set a flag, return from main
basics
~20 sstd::exit runs static destructors, atexit handlers and flushes C streams; std::quick_exit runs only at_quick_exit handlers; std::abort runs nothing; std::terminate calls the terminate handler, which by default calls abort. A daemon should set a flag in its signal handler and return from main.
solid answer
~40 sNone of the four unwinds the stack. `std::exit` destroys thread-local and static objects, calls `atexit` handlers and flushes C streams. `std::quick_exit` (C++11) calls only `at_quick_exit` handlers, in reverse order, destroys nothing, and then calls `_Exit`, which flushes nothing that C++ promises. `std::abort` runs no handlers and no destructors. `std::terminate` calls the current terminate handler, whose default calls `abort`. For the daemon, the signal handler may only do signal-safe things: `std::exit` is not signal-safe, while `quick_exit` is when its handlers are. The robust design stores to a lock-free `std::atomic<bool>` in the handler, lets the main loop notice it, and returns from `main`, so every destructor, including the log's, runs.
code
cpp · 22 lines#include <atomic>
#include <csignal>
#include <fstream>
#include <iostream>
std::atomic<bool> stop_requested{false}; // lock-free on mainstream targets
static_assert(std::atomic<bool>::is_always_lock_free);
extern "C" void on_sigterm(int) { stop_requested.store(true); } // signal-safe: no exit() here
int main() {
std::signal(SIGTERM, on_sigterm);
std::ofstream log("daemon.log"); // buffered; flushed by its destructor
int ticks = 0;
while (!stop_requested.load()) {
log << "tick " << ++ticks << '\n';
if (ticks == 3) std::raise(SIGTERM); // stand-in for `kill <pid>`
}
log << "shutting down cleanly\n";
std::cout << "wrote " << ticks << " ticks\n";
return 0; // ~ofstream runs: log is flushed and closed
}go deeper
Know that std::exit, std::abort and std::terminate all end the program but differ in how much cleanup runs.
Fill in the table: which of exit, quick_exit, abort and terminate destroy statics, run which handlers and flush C streams.
Design daemon shutdown around a lock-free flag and a normal return from main, and choose quick_exit or abort deliberately for the cases where cleanup itself is risky.
Write down the process's shutdown contract: which paths flush logs, which skip static destruction, and how watchdogs and orchestrators are expected to stop it.
## Four ways to end a C++ program early | Function | Destroys automatic objects | Destroys static objects | Runs registered handlers | Flushes C streams | Signal-safe | |---|---|---|---|---|---| | `std::exit(status)` | no | yes | `atexit` ones | yes | no | | `std::quick_exit(status)` (C++11) | no | no | `at_quick_exit` ones | not promised | yes, if its handlers are | | `std::abort()` | no | no | none | not promised | yes | | `std::terminate()` | no (calls the handler) | no | the terminate handler | not promised | not listed | Details from the standard: - `std::quick_exit` calls the functions registered with `std::at_quick_exit` in reverse order of registration, states that "objects shall not be destroyed as a result of calling `quick_exit`", and then calls `_Exit(status)`. `_Exit` terminates without running destructors or `atexit` functions. - `std::abort` terminates without executing destructors for objects of automatic, thread or static storage duration and without calling `atexit` functions. - `std::terminate` calls the current `terminate_handler`; the implementation's default handler calls `abort()`. A run with output redirected to a file showed the difference plainly: `exit` kept every line, `quick_exit` lost even the `at_quick_exit` handler's own `printf` line because the `stdout` buffer was never flushed, and the two aborting paths exited with status 134. Whether `abort` flushes C streams is left to the C library; one run is not a promise. ## The daemon's shutdown The requirement is that log lines already written reach the file when the daemon receives `SIGTERM`. The signal handler is the wrong place to do the work, because a C++ signal handler may only perform **signal-safe** evaluations. Calls to standard library functions are excluded unless they are plain lock-free atomic operations or are explicitly marked signal-safe. `_Exit`, `abort` and `quick_exit` (when its handlers are) carry that mark; `std::exit`, stream output and memory allocation do not. The robust pattern: 1. The handler stores `true` into a `std::atomic<bool>` that is lock-free (a `volatile std::sig_atomic_t` also works). 2. The main loop checks the flag on each iteration and leaves the loop. 3. `main` returns. Every destructor runs, including the `std::ofstream` that holds the log, which flushes and closes it. When the daemon must exit **immediately**, for example from a watchdog, `std::quick_exit` with `at_quick_exit` handlers that do only signal-safe work is the controlled option; `std::abort` is reserved for states where running any more code is dangerous. ## Choosing between them - **Normal shutdown**: return from `main`. - **Fatal error with a consistent state**: throw an exception that `main` catches, or call `std::exit` where no locals matter. - **Fatal error where static destructors could hang or crash**, such as other threads still using statics: `std::quick_exit` with handlers that flush only what matters. - **Corrupted state or a failed invariant**: `std::abort`, usually through an assertion, so a core dump captures the state. - **Exception-handling failure**: `std::terminate` is what the runtime calls itself; calling it directly is rare outside a terminate handler. ## Testing the shutdown path A daemon's shutdown is code that runs once per deployment, so it rots unless a test exercises it: - Start the daemon in a test harness, let it write a few log lines, then send `SIGTERM`. - Assert that the process exits with status `0` within a deadline, not with an abort status. - Assert that the log file's last line is the shutdown message, which proves the stream's destructor ran. - Repeat while worker threads are busy, since shutdown with active threads is where static-destruction races and hangs show up. The snippet below uses `std::raise(SIGTERM)` to deliver the signal to itself, which is enough to exercise the flag-and-return path in a unit test. ## Traps - `std::at_quick_exit` and `std::atexit` keep **separate** lists; a function registered with one does not run on the other path. - An `at_quick_exit` handler runs on the thread that called `quick_exit`, so it cannot rely on that thread's `thread_local` objects being the ones it registered with. - A handler registered with either function that exits via an exception calls `std::terminate`.
- Why does quick_exit exist if std::exit already runs cleanup?Because static destructors can be the problem: in a multithreaded program, other threads may still be using static objects, and destroying them races with that use. `std::quick_exit` skips static destruction entirely and runs only the handlers registered with `at_quick_exit`, so a program can flush what matters and leave without touching shared statics. It was added in C++11 for that reason.
- Is calling std::exit from a signal handler acceptable?No. A signal handler may perform only signal-safe evaluations, and `std::exit` is not identified as signal-safe; it runs destructors and handlers that may take locks or allocate while the interrupted code holds them. `_Exit`, `abort` and `quick_exit` (if its handlers are signal-safe) are allowed; the usual design sets a lock-free atomic flag instead.
- std::quick_exit runs atexit handlers, just faster.
- std::abort flushes all output buffers first.
- Calling std::exit from a SIGTERM handler is a clean shutdown.
- std::terminate unwinds the stack before stopping.
- Any of the four functions runs destructors of local objects.