gpt4 book ai didi

rust - 你会如何在 Rust 中流式传输进程的输出?

转载 作者:行者123 更新时间:2023-11-29 08:11:50 25 4
gpt4 key购买 nike

这个问题指的是截至 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com