如何确保每次迭代后都释放每个“子"进程的文件句柄? [英] How do I make sure that file handle for every `Child` process is released after every iteration?

查看:144
本文介绍了如何确保每次迭代后都释放每个“子"进程的文件句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序是从Rust文档中获取的. > .经过一些迭代后,它将停止工作.

I have the following program taken from the Rust docs for std::process::Command. It stops working after some iterations.

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));
    }
}

每次崩溃时,我都会收到以下输出:

Every time it crashes, I receive the following output:

thread 'main' panicked at 'failed to start 'sed': Error { repr: Os { code: 35, message: "Resource temporarily unavailable" } }', src/libcore/result.rs:906:4

根据 Child 的文档(我从那里获取该程序的地方),上面写着:

According to the docs for Child (where I took this program from), it says:

对于子进程没有Drop的实现,因此如果您这样做 不确保Child已退出,那么它将继续运行,即使 子进程的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进程的文件句柄在每次迭代后都释放?

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

推荐答案

如果您在引用该段落之后立即阅读该段落:

If you read the paragraph immediately after the one you have quoted:

调用wait(或其他环绕它的函数)将使父进程等待直到子进程实际退出后再继续.

Calling wait (or other functions that wrap around it) will make the parent process wait until the child has actually exited before continuing.

要呼叫wait,您无需将stdoutChild中移出:

In order to call wait, you need to not move stdout out of Child:

let echo_out = echo_child.stdout.take().expect("failed to open 'echo' stdout");

// ...

echo_child.wait().expect("Couldn't wait for echo child");

另请参阅:

这篇关于如何确保每次迭代后都释放每个“子"进程的文件句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆