C++中exec*()函数对常规退出保证的影响探究
Great question—this is a common gotcha when mixing Unix-style exec() calls with C++ runtime behavior. Let’s break down each of your concerns clearly:
Automatic (Stack) Variables
- No, their destructors will not run. When
exec()succeeds, it replaces the entire process address space—code, stack, heap, everything—with the new program. There’s no "stack unwinding" because the original stack is overwritten immediately. If you callexec()from inside a function with local variables, those variables will never get a chance to be destroyed, since the function never "returns" in the normal sense.
Thread-Local Storage (TLS) Variables
- No, their destructors won’t execute.
exec()terminates all threads except the one that called it, and the entire TLS region of the original process is replaced by the new program’s TLS. The original TLS variables are gone before any destructor could run.
Static/Global Variables
- No, they won’t be destroyed. Static and global variable destructors are triggered by the C++ runtime when the program exits normally (via
exit(),returnfrommain(), etc.). Butexec()replaces the entire process, including the original C++ runtime—so those destructors are never invoked.
std::atexit() Callbacks
- No, they won’t run.
std::atexit()registers functions to be called whenexit()is invoked. Sinceexec()does not callexit()(it replaces the process instead), these callbacks are never executed.
Critical Caveat
All of this only applies if exec() succeeds. If exec() fails (e.g., the target program doesn’t exist, permission denied), the original process continues running as normal. In that case, your usual C++ exit guarantees do hold: stack unwinding will happen when functions return, static/global destructors will run if you later call exit(), and std::atexit() callbacks will execute as expected.
In short: exec() success means your original program’s C++ runtime and all its cleanup logic are discarded entirely. Only on failure do you fall back to normal C++ behavior.
内容的提问来源于stack exchange,提问作者Ad N

