rust - 如何确保在每次迭代后释放每个 `Child` 进程的文件句柄?

标签 rust file-descriptor systems-programming

我采取了以下程序 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");

另见:

关于rust - 如何确保在每次迭代后释放每个 `Child` 进程的文件句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547534/

相关文章:

macros - Rust 派生宏中的无限递归?

rust - 如何改变 Rust 中的迭代器元素以反转子字符串

rust - 如何计算两个 Rust 数组/切片/向量的点积?

c - 关于在c中更改文件描述符编号的问题

c++ - 为什么 UNIX 文件描述符不是由它们自己的类型实现的,尤其是在 C++ 中?

assembly - 文字 VS 立即操作数

c++ - C 和 C++ 标准是否暗示地址空间中的特殊值必须仅存在以表示空指针的值?

rust - 轮询许多不同类型的 future

linux x86 汇编语言 sys_read 调用的第一个参数应该为 0 (stdin)

c - 僵尸进程