You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中exec*()函数对常规退出保证的影响探究

Will C++ Exit Guarantees Hold When Using exec() Family Functions?

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 call exec() 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(), return from main(), etc.). But exec() 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 when exit() is invoked. Since exec() does not call exit() (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:42:54