Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cleanly end the program with an exit code?

Tags:

rust

Is there a way of returning an exit code in Rust 1.0?

I've tried env::set_exit_status(exit_code); but this generates a compiler error.

There is also this question: Exit Rust program early which is similar but asks about the case when the process has to be exited early.


EDIT: I'm looking for a solution that will also allow the process to tidy up the stack, call destructors, etc.

like image 200
Thomas Bratt Avatar asked May 16 '15 22:05

Thomas Bratt


People also ask

What is the meaning of process finished with exit code?

exit code (0) means an exit without errors or issues. exit code (1) means there was some issue / problem which caused the program to exit. The effect of each of these codes can vary between operating systems, but with Python should be fairly consistent.

How to immediately exit program in c?

Some of the common ways to terminate a program in C are: exit. _Exit() quick_exit.

How to force stop in c program?

The exit() function is used to terminate program execution and to return to the operating system. The return code "0" exits a program without any error message, but other codes indicate that the system can handle the error messages. Syntax: void exit(int return_code);


2 Answers

Building over the comments of @FrancisGagné 's answer, if you are searching for an equivalent of C's return exit_code, you can artificially build it this way:

fn main() {
    let exit_code = real_main();
    std::process::exit(exit_code);
}

fn real_main() -> i32 {
    // the real program here
}

This way, all the objects of your program will be in the scope of the real_main() function, and you can safely use return exit_code; in main while still having all destructors properly run.

like image 191
Levans Avatar answered Oct 28 '22 14:10

Levans


std::process::exit exits the program with the specified exit code.

like image 44
Francis Gagné Avatar answered Oct 28 '22 14:10

Francis Gagné