如何确保在每次迭代后释放每个“子”进程的文件句柄?

How do I make sure that file handle for every `Child` process is released after every iteration?

我参加了以下课程 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 the Child has exited then it will continue to run, even after the Child 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");

另请参阅:

  • Kill child process while waiting for it