[英]How to get the exit code of a Bash script running from inside a Rust program?
I've been trying to wrap my head around a few simple implementations of systems programming involving the ability to call Bash from C and Rust.我一直在尝试围绕一些简单的系统编程实现来解决问题,这些实现涉及从 C 和 Rust 调用 Bash 的能力。 I was curious if there was a way to modify the following statement, in Rust specifically, to allow me to get a return value of
4
from a Bash script that runs in the following manner:我很好奇是否有办法修改以下语句,特别是在 Rust 中,以允许我从以以下方式运行的 Bash 脚本获得返回值
4
:
let status = Command::new("pathtoscript").status().expect("failed to execute process");
Rust String stuff confuses me initially, but any combination of actions that leads to status granting me access to the value of 4
being returned to the parent process would be great . Rust 字符串的东西最初让我感到困惑,但是任何导致状态授予我访问返回给父进程的值
4
的操作组合都会很棒。 Thank you so much in advance for helping me.非常感谢您提前帮助我。 I have checked the Rust documentation but I haven't found anything for getting things BACK to the parent process, only to the child process.
我已经检查了 Rust 文档,但我没有找到任何东西可以让事情回到父进程,只有子进程。
I should say it goes without saying for my application writing to a file and reading from that file is not sufficient or secure enough.我应该说,我的应用程序写入文件并从该文件读取是不够的或不够安全的,这是不言而喻的。
If you need the exit code 4
use status.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
}
My script.sh
file:我的
script.sh
文件:
#!/bin/bash
# Will exit with status of last command.
# exit $?
# echo $?
# Will return 4 to shell.
exit 4
And see this too:也看到这个:
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.