我有一个长时间运行的子进程,需要读写大量数据。我有一个读取线程和一个写入线程来分别处理 child.stdout
和 child.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()
,因为它被两个线程借用。我该如何使这个程序完整?
communicate
方法,用于您现在使用线程的操作。它还公开了一种构建器样式的API,可以将上述表达为let input = (0..1000).map(|i| format!("{}", i)).collect::<String>(); let output = Exec::cmd("cat").stdin(input).stdout(Redirection::Pipe).capture()?.stdout_str();
免责声明:我是subprocess的作者。 - user4815162342