我有以下程序from the Rust docs for std::process::Command
。它经过一些迭代后停止工作。
use std::process::Command;
use std::process::Stdio;
fn main() {
loop {
let mut echo_child = Command::new("echo")
.arg("oh no a tpyo")
.stdout(Stdio::piped())
.spawn()
.expect("failed to start 'echo'");
let echo_out = echo_child.stdout.expect("failed to open 'echo' stdout");
let sed_child = Command::new("sed")
.arg("s/tpyo/typo/")
.stdin(Stdio::from(echo_out))
.stdout(Stdio::piped())
.spawn()
.expect("failed to start 'sed'");
let sed_out = sed_child
.wait_with_output()
.expect("failed to wait on 'sed'");
let sed_out_slice = sed_out.stdout.as_slice();
assert_eq!(b"oh no a typo\n", sed_out_slice);
println!("out: {:?}", String::from_utf8_lossy(sed_out_slice));
}
}
每次崩溃时,我都会收到以下输出:
thread 'main' panicked at 'failed to start 'sed': Error { repr: Os { code: 35, message: "Resource temporarily unavailable" } }', src/libcore/result.rs:906:4
根据the docs for Child
(我从中获取此程序),它说:
子进程没有
Drop
的实现,所以如果你这样做了 不确保Child
退出,然后它将继续运行,甚至 在子进程的Child
句柄超出范围之后。
如何确保每次迭代后释放每个Child
进程的文件句柄?
答案 0 :(得分:1)
如果您在引用的段落之后立即阅读该段落:
调用
wait
(或其他包含它的函数)将使父进程等待,直到子进程实际退出为止。
要致电wait
,您无需将stdout
移出Child
:
let echo_out = echo_child.stdout.take().expect("failed to open 'echo' stdout");
// ...
echo_child.wait().expect("Couldn't wait for echo child");
另见: