Search code examples
rustexitatexit

What's the best way to register a function to run during an unexpected exit of a Rust program?


I'm creating a terminal text editor in Rust. The editor puts the terminal into raw mode, disabling character echoing and the like, and then restores the original terminal function upon exit.

However, the editor has some bugs, and crashes unexpectedly every now and again due to issues like unsigned variable underflow. When this happens, the cleanup code which would restore the terminal to its original state never runs.

The cleanup function I'd like to run is the following:

fn restore_orig_mode(editor_config: &EditorConfig) -> io::Result<()> {
    termios::tcsetattr(STDIN, termios::TCSAFLUSH, &editor_config.orig_termios)
}

Solution

  • Try catch_unwind. I haven't used it, so I cannot guarantee it works.