gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:59:37 25 4
gpt4 key购买 nike

我有一个长时间运行的子进程,我需要向其读取和写入大量数据。我有一个读取器线程和一个写入器线程,分别操作 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() 因为它被两个线程借用了。

如何完成这个程序?

最佳答案

有趣的是,这是您自己通过使用 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();

关于rust - 读取和写入长时间运行的 std::process::Child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46873877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com