Cleanup on exit
⚓ Rust 📅 2025-12-25 👤 surdeus 👁️ 13I'm writing a console application that needs to do some cleanup when it exits. It opens an alternate screen buffer, changes bg/fg colors, a bunch of things like that that I'd like to revert when the user terminates the app. I understand that there's no 100% reliable way to do this but I'd like it to work in as many cases as possible. Note that this also needs to work on Windows.
What I have so far is the following:
- A scope guard in my main function that handles the case of a graceful termination.
- A panic handler that will clean up on every panic (my application is single-threaded right now and never tries to recover from a panic). Not sure if this is necessary or if I can rely on unwind dropping my scope guard instead.
- The
ctrlclibrary to handle the most common termination signals. The handler will prevent shutdown and instead set a termination flag in my application to make it exit gracefully.
Is the panic handler the correct approach? Is there any way to intercept a call to exit()? Anything else that I'm missing?
2 posts - 2 participants
🏷️ Rust_feed