How to ensure calling `Drop` before the program exits?

I know that, ensure Drop trait being called before the program exit is not feasible (for example, when an atom bomb force the program to stop running), but is there something that allow calling Drop before the program exits?

When panic = unwind is set, I tried registering a function for libc::atexit that executing panic!("executing unwind"), which unwind the whole stack, drop every resources it could touch. But an annoying panic message occurs.

I checked the implementation, it seems that I could call panic_impl directly, but that op requires a nightly feature, panic_internal, which cannot be used in stable rust.

Is there some better way to unwind the stack?

What's more, when I tried to handle more conditions with libc::atexit, I cannot register that function since libc does not accept functions with signature extern "C-unwind" fn() {unwind}.

So, what is the best way to drop important variables before exiting rust program? Should I just examine all the possible exit path and marks them manually?

Your subject says "ensure". Anything can just call std::process::exit, so the answer to that one is no. There is no guarantee.

This part says "allows". Sure, call drop(thing) or have the value go out of scope, e.g. by returning up the call stack.[1] This is the typical way Rust programs act, especially panic=unwind programs.

Most of the rest of the post is talking about forcing an unwind. You can just panic!, but there's no guarantee something won't catch the unwind, or that a Drop implementation won't also panic and cause an abort.

You can std::panic::set_hook(Box::new(|_| {})); to get rid of the message.


  1. There's other ways too, e.g. with unsafe ↩ī¸Ž

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.