linux - 如何获取从 Rust 程序内部运行的 Bash 脚本的退出代码?

标签 linux bash rust

我一直在努力思考一些简单的系统编程实现,涉及从 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/

相关文章:

linux - 如何撤销svn checkout

Linux shell 中的 python 导出环境变量

python - 如何在 bash 中提示用户输入?请修复我的 python/bash Spanglish

rust - 如何为特征实现指定引用生命周期?

multithreading - 为什么 Rust playground 不会为线程产生不同的结果?

linux - echo 2 >/proc/sys/net/ipv4/tcp_mtu_probing 能够解决我的问题,但为什么呢?这个命令是做什么的?

linux - 为模式之间的文本创建新文件

php - 使用短标签从命令行运行 php

bash - passwd:当我运行我创建的 Bash 脚本时,Debian 上出现无法识别的选项 '--stdin' 错误

rust - 这些迭代向量的方法有什么不同吗?