我一直在努力思考一些简单的系统编程实现,涉及从 C 和 Rust 调用 Bash 的能力。我很好奇是否有一种方法可以修改以下语句,特别是在 Rust 中,以允许我从按以下方式运行的 Bash 脚本中获取 4
的返回值:
let status = Command::new("pathtoscript").status().expect("执行进程失败");
Rust String 的东西最初让我感到困惑,但是任何导致状态授予我访问返回给父进程的 4
值的操作组合都是很棒 .非常感谢你提前帮助我。我已经检查了 Rust 文档,但我没有找到任何东西可以将东西返回到父进程,只返回到子进程。
我应该说,我的应用程序写入文件并从该文件读取是不充分或不够安全的,这是不言而喻的。
最佳答案
如果需要the exit code 4
使用 status.code()
:
use std::process::Command;
fn main() {
let status = Command::new("./script.sh")
.status()
.expect("failed to execute process");
println!("{}", status.code().unwrap()); // 4
}
我的script.sh
文件:
#!/bin/bash
# Will exit with status of last command.
# exit $?
# echo $?
# Will return 4 to shell.
exit 4
还有这个:
use std::process::Command;
let status = Command::new("mkdir")
.arg("projects")
.status()
.expect("failed to execute mkdir");
match status.code() {
Some(code) => println!("Exited with status code: {}", code),
None => println!("Process terminated by signal")
}
关于linux - 如何获取从 Rust 程序内部运行的 Bash 脚本的退出代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585566/