我采取了以下程序 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
(我从哪里得到这个程序),它说:
There is no implementation of
Drop
for child processes, so if you do not ensure theChild
has exited then it will continue to run, even after theChild
handle to the child process has gone out of scope.
如何确保在每次迭代后释放每个 Child
进程的文件句柄?
最佳答案
如果您在引用的段落之后立即阅读段落:
Calling
wait
(or other functions that wrap around it) will make the parent process wait until the child has actually exited before continuing.
为了调用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");
另见:
关于rust - 如何确保在每次迭代后释放每个 `Child` 进程的文件句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547534/