rust - 如何定时查询子进程状态

标签 rust

我使用 Rust 的 Command 生成了一个子进程API。

现在,我需要在继续之前观察这个过程几秒钟,因为这个过程可能会提前结束。成功后,它应该“永远”运行,所以我不能等待。

有一个夜间功能称为 try_wait它可以满足我的要求,但我真的不认为我应该为此每晚运行 Rust!

我想我可以启动一个新线程并让它一直等待或直到进程终止...但我不想让我的进程与该线程挂起,所以也许将线程作为守护进程运行可能是一种解决方案。 ..

这是要走的路还是有更好的解决方案?

最佳答案

目前,如果您不想使用夜间 channel ,可以使用一个名为 wait-timeout 的箱子(感谢@lukas-kalbertodt 的建议)将 wait_timeout 函数添加到 std::process::Child特质。

可以这样使用:

let cmd = Command::new("my_command")
    .spawn();

match cmd {
    Ok(mut child) => {
        let timeout = Duration::from_secs(1);

        match child.wait_timeout(timeout) {
            Ok(Some(status)) => println!("Exited with status {}", status),
            Ok(None) => println!("timeout, process is still alive"),
            Err(e) => println!("Error waiting: {}", e),
        }
    }
    Err(err) => println!("Process did not even start: {}", err);
}

要继续监视子进程,只需将其包装到一个循环中即可。

注意使用 Rust 的 nightly try_wait() , 代码看起来几乎相同(所以一旦它进入发布分支,假设没有进一步的变化,应该很容易移动到那个),但它会阻塞给定的 timeout 即使与上面的解决方案不同,该进程比这更早结束:

let cmd = Command::new("my_command")
    .spawn();

match cmd {
    Ok(mut child) => {
        let timeout = Duration::from_secs(1);
        sleep(timeout); // try_wait will not block, so we need to wait here
        match child.try_wait() {
            Ok(Some(status)) => println!("Exited with status {}", status),
            Ok(None) => println!("timeout, process is still alive"),
            Err(e) => println!("Error waiting: {}", e),
        }
    }
    Err(err) => println!("Process did not even start: {}", err);
}

关于rust - 如何定时查询子进程状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43705010/

相关文章:

macros - 为什么我不能访问在宏中声明的变量,除非我传入变量名?

rust - 在 HashMap 中存储闭包

rust - 我应该使用 Rust 1.0-alpha 还是 nightly 版本?

asynchronous - 如何在 Rust Hyper 中将响应主体读取为字符串?

rust - 移动结构时如何自动清除结构中的属性?

c - 从 Rust FFI 访问 DPDK 中的静态 C 函数

closures - 为什么值是移入这里的闭包而不是借来的?

generics - 泛型结构的构造函数中出现 "Expected type parameter"错误

rust - 将二进制数字字符串转换为 Rust 中的实际数字的内置方法?

operator-overloading - 如何为不同的 RHS 类型和返回值重载运算符?