【问题标题】:Why does Command.output() execution sometimes return None for status.code()为什么 Command.output() 执行有时会为 status.code() 返回 None
【发布时间】:2019-07-15 22:29:44
【问题描述】:

我的 rust 项目使用Command 来执行一个进程。

有时(低频)当我运行此代码时,对status.code() 的调用返回无。我通常使用 Mac OS Catalina Beta 1,rustc 1.36.0 - 但它也发生在 Travis 中(必须去那里找到 OS/rustc 的日志)。

我将此视为错误,但“随机”会导致本地和 travis 构建失败,所以现在我忽略它 - 但很高兴了解导致它的原因。

在失败的情况下,立即重新运行将使其成功。

let output = Command::new(&command)
    .args(command_args)
    .stdin(Stdio::inherit())
    .stdout(Stdio::inherit())
    .stderr(Stdio::piped())
    .output()
    .chain_err(|| "Error while attempting to spawn command to compile and run flow")?;
match output.status.code() {
    Some(0) => Ok("Flow ran to completion".to_string()),
    Some(code) => {
        error!(
            "Process STDERR:\n{}",
            String::from_utf8_lossy(&output.stderr)
        );
        bail!("Exited with status code: {}", code)
    }
    None => Ok("No return code - ignoring".to_string()),
}

我的问题不是为什么会发生这种情况可能(我知道文档说“由信号终止”)而是为什么会发生这种情况,因为没有人 AFAIK向它发送信号,我严重怀疑任何 OOM 或其他此类问题。

【问题讨论】:

标签: rust


【解决方案1】:

阅读manual:

在 Unix 上,如果进程被信号终止,这将返回 None; std::os::unix 提供了一个扩展 trait,用于从 ExitStatus 中提取信号和其他细节。

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

fn main() {
    let mut child = Command::new("sleep")
        .args(&["10"])
        .spawn()
        .expect("failed to spawn child");
    child.kill().expect("failed to kill on child");
    let status = child.wait().expect("failed to wait on child");
    match status.code() {
        None => {
            println!("{:?}", status.signal());
            ()
        }
        _ => (),
    }
}

您可以使用from_c_int() 来漂亮地打印信号类型。

【讨论】:

  • 我已经有了,并且我的失败日志用于打印“进程被信号终止”,但这并不能帮助我理解它为什么会发生,以及该信号来自哪里以及为什么正在发送。
  • @AndrewMackenzie 我怎么知道,先看看doc.rust-lang.org/nightly/std/os/unix/process/…收到了什么信号。
  • @AndrewMackenzie 发送信号的是你系统上的东西,(很可能)不是你自己的程序。找出这一点将是一个完全不同的问题,相关信息不是您的代码,而是您如何运行程序以及您获得的信号。这更像是一个Unix & Linux 问题而不是Stack Overflow 问题。
猜你喜欢
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多