[英]How to get the exit code of a Bash script running from inside a Rust program?
我一直在嘗試圍繞一些簡單的系統編程實現來解決問題,這些實現涉及從 C 和 Rust 調用 Bash 的能力。 我很好奇是否有辦法修改以下語句,特別是在 Rust 中,以允許我從以以下方式運行的 Bash 腳本獲得返回值4
:
let status = Command::new("pathtoscript").status().expect("failed to execute process");
Rust 字符串的東西最初讓我感到困惑,但是任何導致狀態授予我訪問返回給父進程的值4
的操作組合都會很棒。 非常感謝您提前幫助我。 我已經檢查了 Rust 文檔,但我沒有找到任何東西可以讓事情回到父進程,只有子進程。
我應該說,我的應用程序寫入文件並從該文件讀取是不夠的或不夠安全的,這是不言而喻的。
如果您需要退出代碼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")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.