Search code examples
c++linux

How to Gracefully Terminate Process In C++?


By "Gracefully" I mean: "Call local/static objects dtor before terminating without generating coredump".

I tried:

  • std::exit() (Teminates with coredump)
  • std::_Exit()
  • std::abort() (Teminates with coredump)
  • std::raise(SIGKILL)
  • std::terminate() (Teminates with coredump)

They all terminate the process immediately without calling local/static objects dtor. My problem is: In my code base, I have some errors that can't be tolerated and the process should be terminated; but, also I have some global/local objects(e.g. loggers) that need dtor to be called before termination.


  • Compiler: Clang 12
  • OS: Linux 5.10.0-1
  • Arch: Aarch64

Solution

  • If you want local variables to be destroyed correctly, then your only solutions are to return back through the call stack, up to and including main, or to throw an exception that you catch in main to then return from it.

    However, the behavior you state for different library calls in your question is not correct, specifically std::exit() exits normally. A core dump should not be produced and although it doesn't destroy variables with automatic storage duration, it will call the destructors of static storage duration objects.

    std::_Exit also exits normally, but contrary to std::exit doesn't do any clean up (not static storage duration objects or std::at_exit/std::at_quick_exit handlers either).

    The other three calls cause abnormal program termination, which doesn't seem what you want.

    std::raise(SIGKILL) inheriently doesn't perform any kind of clean-up. It just raises SIGKILL. The exact behavior will be OS-dependent. At least for Linux it will immediately cause the kernel to terminate the process without it ever being able to regain control.

    std::terminate() will call the (possibly user-provided) terminate handler. The default terminate handler calls std::abort.

    std::abort causes the SIGABRT signal to be raised without any clean-up (just like std::_Exit, but abnormally). The signal might be caught or end up with the process being killed immediately if not.

    None of them perform stack unwinding to destroy local variables with automatic storage duration.