Why doesn't exit unwind?


#1

It seems a little odd that a safe function will bypass destructors. Is there any reason std::process::exit doesn’t unwind the stack? Personally, I think we need two functions:

fn std::process::exit(code: i32);
unsafe fn std::process:exit_now(code: i32);

Cleanly exiting the program in Rust
#2

It is currently not considered unsafe to leak memory or resources in Rust. For example:

  • You can trivially create a cycle using Rc + RefCell that will leak and never destroy its contents
  • You can exit the main thread while other threads are running, not running their destructors

As a result, not running destructors is not considered unsafe, so this function was introduced as safe


#3

Got it. I always forget that unsafe only refers to memory access, not general behavior.

As a result, not running destructors is not considered unsafe, so this function was introduced as safe.

Just for complete correctness in case anyone comes across this thread later, this isn’t always true. Failing to call a destructor before freeing or failing to call a destructor on drop is unsafe. there is no guarantee that a destructor will ever be called.


#4

Unsafe or not, the design of this function seems off to me. What’s the reason behind not calling destructors by default?

I see two distinct use cases here:

  1. Choosing a custom error code

  2. Aborting the program without doing any cleanup

The current exit() conflates these two cases, when most of the time you only want the first.


#5

For what it’s worth, the KJ C++ library also encourages RAII style together with a non-unwinding exit(), and its documentation gives some well thought out justification.