How do I exit a Rust program early from outside the main function?

前端 未结 2 1064
故里飘歌
故里飘歌 2020-12-30 19:11

I am in the process of writing a bash clone in Rust. I need to have my program exit when the user types exit. In previous iterations of my progra

2条回答
  •  情话喂你
    2020-12-30 19:39

    Rust 1.0 stable

    std::process::exit() does exactly that - it terminates the program with the specified exit code:

    use std::process;
    
    fn main() {
        for i in 0..10 {
            if i == 5 {
                process::exit(1);
            }
            println!("{}", i);
        }
    }
    

    This function causes the program to terminate immediately, without unwinding and running destructors, so it should be used sparingly.

    Alternative (not recommended) solution

    You can use C API directly. Add libc = "0.2" to Cargo.toml, and:

    fn main() {
        for i in 0..10 {
            if i == 5 {
                unsafe { libc::exit(1); }
            }
            println!("{}", i);
        }
    }
    

    Calling C functions cannot be verified by the Rust compiler, so this requires the unsafe block. Resources used by the program will not be freed properly. This may cause problems such as hanging sockets. As far as I understand, the proper way to exit from the program is to terminate all threads somehow, then the process will exit automatically.

提交回复
热议问题