如何从主函数外部提前退出 Rust 程序? [英] How do I exit a Rust program early from outside the main function?

查看:108
本文介绍了如何从主函数外部提前退出 Rust 程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Rust 编写一个 bash 克隆.当用户输入 exit 时,我需要让我的程序退出.在我程序的先前迭代中,在添加更复杂的功能之前,我使用 return 来退出提示用户输入的循环.这个逻辑现在在一个函数中,因为我实现内置 shell 函数的方式,所以当我 return 它只是跳出函数回到控制循环,而不是短路控制循环并结束程序.

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 program, before I added more complicated features, I used return to get out of the loop that was prompting the user for input. This logic is now in a function, because of the way I am implementing built in shell functions, so when I return it just jumps out of the function back into the control loop, instead of short-circuiting the control loop and ending the program.

我意识到当用户输入 exit 并退出循环时,我可能会返回一个布尔值,但我想至少知道 Rust 是否有办法提前终止程序,类似于 Java 的System.exit(),因为这对某些类型的程序很有用.

I realize that I could probably return a boolean when the user types exit and exit the loop, but I would like to at least know if Rust has a way to terminate programs early, similar to Java's System.exit(), as this is useful for certain types of programs.

推荐答案

Rust 1.0 stable

std::process::exit() 正是这样做的 - 它使用指定的退出代码终止程序:

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.

您可以直接使用 C API.将 libc = "0.2" 添加到 Cargo.toml,并:

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);
    }
}

Rust 编译器无法验证调用 C 函数,因此这需要 unsafe 块.程序使用的资源将不会被正确释放.这可能会导致诸如挂插座之类的问题.据我了解,退出程序的正确方法是以某种方式终止所有线程,然后进程将自动退出.

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.

这篇关于如何从主函数外部提前退出 Rust 程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆