rust - 如何从 Rust 中的进程流输出?

标签 rust rust-obsolete

此问题涉及截至 2014 年 10 月的 Rust。

如果您使用 Rust 1.0 或更高版本,您最好在其他地方寻找解决方案。


我有一个长时间运行的 Rust 进程,它生成日志值,我正在使用 Process 运行该进程。 .

它看起来我也许能够使用 set_timeout()wait() 定期“检查”正在运行的进程,并执行某种高级循环像:

let mut child = match Command::new("thing").arg("...").spawn() {
    Ok(child) => child,
    Err(e) => fail!("failed to execute child: {}", e),
};
loop {
    child.set_timeout(Some(100));
    match child.wait() {
        // ??? Something goes here
    }
}

我没有 100% 投入的事情是:如何区分超时错误和 wait() 的进程返回错误,以及如何使用 PipeStream每个间隔“在不阻塞流的情况下尽可能多地读取”以推出。

这是最好的方法吗?我应该启动一个任务来监视 stdout 和 stderr 吗?

最佳答案

为了区分过程中的错误和超时,您必须管理等待的返回,示例如下:

fn run() {
    let mut child = match Command::new("sleep").arg("1").spawn() {
        Ok(child) => child,
        Err(e) => fail!("failed to execute child: {}", e),
    };
    loop {
        child.set_timeout(Some(1000));
        match child.wait() {
            // Here assume any error is timeout, you can filter from IoErrorKind
            Err(..) => println!("Timeout"),
            Ok(ExitStatus(0)) => {
                println!("Finished without errors");
                return;
            }
            Ok(ExitStatus(a)) => {
                println!("Finished with error number: {}", a);
                return;
            }
            Ok(ExitSignal(a)) => {
                println!("Terminated by signal number: {}", a);
                return;
            }
        }
    }
}

关于使用流,请检查 wait_with_output,或使用 channel 和线程实现类似的东西:http://doc.rust-lang.org/src/std/home/rustbuild/src/rust-buildbot/slave/nightly-linux/build/src/libstd/io/process.rs.html#601

希望对你有帮助

关于rust - 如何从 Rust 中的进程流输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550962/

相关文章:

rust - 如何使用在 main 中创建的变量调用需要“静态生命周期”的函数?

parsing - 我如何自己使用 Rust 解析器 (libsyntax)?

rust - 有没有更优雅的方法来用默认字符串解开 Option<Cookie> ?

rust - 如果没有传递到 spawn() 中,则无法推断出 proc() 的类型信息

arrays - 使用常量表达式声明数组的大小

rust - Rust 中的 "0is"表示法是什么?

rust - 使用 '?'运算符对自定义类型进行自动错误转换

java - Rust 中的消息摘要

random - 如何在 Rust 中生成一个范围内的随机数?

rust - 如何在 Rust 0.13.0 中获得平方根?