如何在用户不输入 sudo 的情况下停止程序并使用 sudo 重新启动?

How do I stop the program and restart with sudo without the user typing the word sudo?

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    let mut source_list = OpenOptions::new()
        .write(true)
        .append(true)
        .open("/usr/local/etc/apt/sources.list")
        .unwrap();

    if let Err(e) = writeln!(source_list, "{}", "deb ".to_owned() + "https://www.google.com/" + " ./") {
        eprintln!("Couldn't write to file: {}", e);
    }
}

当 运行 在没有 sudo 的情况下使用此代码时,它输出:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 13, kind: PermissionDenied, message: "Permission denied" }', src/libcore/result.rs:999:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

当 运行使用 sudo 连接此代码时,它会询问我的密码,然后成功写入文件,所以我的问题是如何让它询问我的密码,然后成功写入文件不需要 sudo(基本上我如何为用户制作 运行 sudo,这样他们就不必这样做了)?

Basically how do I make it run sudo for the user so they don't have to

你不能。

这个问题的正常处理方法是尝试,如果失败了,分析错误并礼貌地要求用户以相关权限启动程序:

let source_list = openoptions::new()
        .write(true)
        .append(true)
        .open("/usr/local/etc/apt/sources.list");
match source_list {
    Err(ioerr) => {
        match ioerr.kind() {
            ErrorKind::PermissionDenied => {
                e.println("permission denied. Maybe sudo?");
            }
            _ => {
                e.println("I failed :(");
            }
        }
        return;
    }
    Ok(source_list) => {
        // do things
    }
}

是的,你可以,但如果你应该是另一个问题...

当检测到缺少权限时,您可以使用 sudo 重新启动程序 std::process::Command and unix is extensions exec by executing a command with the same cmdline arguments. env::args 是所有命令行参数的迭代器,其中第一个参数是程序名称

use std::process::Command;
use std::os::unix::process::CommandExt;

 [...]
 // when restart as root is needed
 let cmdlineargs:Vec<String>=env::args().collect();
 let _output = Command::new("sudo")
                    .args(&cmdlineargs)
                    .exec(); // Bye bye never returns

上面的代码有很多问题,例如,您应该避免让程序在无限循环中自行重启,并且对用户隐藏权限升级通常被认为是糟糕的设计。

编辑:在评论中的建议将 spawn 替换为 exec

后更新