读取和写入长时间运行的std :: process :: Child

时间:2017-10-22 12:07:22

标签: rust

我有一个长时间运行的子进程,我需要读取和写入大量数据。我有一个读者线程和一个写作线程分别操纵child.stdoutchild.stdin

extern crate scoped_threadpool;

fn main() {
    // run the subprocess
    let mut child = std::process::Command::new("cat")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    let child_stdout = child.stdout.as_mut().unwrap();
    let child_stdin = std::sync::Mutex::new(child.stdin.as_mut().unwrap());

    let mut pool = scoped_threadpool::Pool::new(2);
    pool.scoped(|scope| {
        // read all output from the subprocess
        scope.execute(move || {
            use std::io::BufRead;
            let reader = std::io::BufReader::new(child_stdout);
            for line in reader.lines() {
                println!("{}", line.unwrap());
            }
        });

        // write to the subprocess
        scope.execute(move || {
            for a in 0..1000 {
                use std::io::Write;
                writeln!(&mut child_stdin.lock().unwrap(), "{}", a).unwrap();
            } // close child_stdin???
        });
    });
}

当编写完成后,我想关闭child_stdin以便子进程完成并退出,以便读者看到EOF并返回pool.scoped。我无法在child.wait()之后执行此操作而无法调用child.wait(),因为它是由两个线程借用的。

如何完成此计划?

1 个答案:

答案 0 :(得分:2)

有趣的是,您通过使用Mutex ^ _ ^分享所有权来自行解决此问题。取代对child.stdin的引用,取得对它的完全所有权并将其传递给线程。当线程结束时,它将被删除,隐式关闭它:

let mut child_stdin = child.stdin.unwrap();

// ...

scope.execute(move ||
    for a in 0..1000 {
        use std::io::Write;
        writeln!(&mut child_stdin, "{}", a).unwrap();
    }
    // child_stdin has been moved into this closure and is now
    // dropped, closing it.
);

如果您仍希望仍然可以致电wait来获取ExitStatus,请将引用更改为stdout并转让stdin的所有权使用Option::take。这意味着child根本没有借用:

let mut child = // ...

let child_stdout = child.stdout.as_mut().unwrap();
let mut child_stdin = child.stdin.take().unwrap();

// ...

child.wait().unwrap();