Rust 连续处理子进程';使用BufReader逐字节输出

Rust 连续处理子进程';使用BufReader逐字节输出,rust,process,command,pipe,Rust,Process,Command,Pipe,我正在尝试与外部命令(在本例中为exiftool)交互并逐字节读取输出,如下例所示。 如果我愿意先读入所有输出并等待子进程完成,那么我可以让它工作,但使用BufReader似乎会导致无限期地等待第一个字节。我使用BufReader作为访问标准输出的参考 使用std::io::{Write,Read}; 使用std::process::{Command,Stdio,ChildStdin,ChildStdout}; fn main(){ 让mut child=Command::new(“exifto

我正在尝试与外部命令(在本例中为exiftool)交互并逐字节读取输出,如下例所示。 如果我愿意先读入所有输出并等待子进程完成,那么我可以让它工作,但使用BufReader似乎会导致无限期地等待第一个字节。我使用BufReader作为访问标准输出的参考

使用std::io::{Write,Read};
使用std::process::{Command,Stdio,ChildStdin,ChildStdout};
fn main(){
让mut child=Command::new(“exiftool”)
.arg(“-@”)/“从文件中读取命令行选项”
.arg(“-”/)将标准输入用于-@
.arg(“-q”)/“安静处理”(仅向标准输出发送图像数据)
.arg(“-previewImage”)//用于提取缩略图
.arg(“-b”)/“以二进制格式输出元数据”
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn().unwrap();
{
//通过标准输入传递输入文件名
设stdin:&mut ChildStdin=child.stdin.as_mut().unwrap();
stdin.write_all(“IMG_1709.CR2.as_bytes()).unwrap();
//休假范围:
//“当删除ChildStdin的实例时,ChildStdin的底层文件句柄将被删除
//关闭。”
}
//这不起作用:
让stdout:ChildStdout=child.stdout.take().unwrap();
让reader=std::io::BufReader::new(stdout);
对于reader.bytes().enumerate()中的(byte_i,byte_值){
//这一行永远不会打印,程序似乎也不会终止:
println!(“获取的字节{}:{}”,字节_i,字节_value.unwrap());
// …
打破
}
//这项工作:
让output=child.wait_with_output().unwrap();
for(byte_i,byte_value)在output.stdout.iter()枚举()中{
println!(“获得的字节{}:{}”,字节i,字节值);
// …
打破
}
}

您没有关闭孩子的stdin。您的
stdin
变量是一个可变引用,删除它对引用的
ChildStdin
没有影响

使用
child.stdin.take()
代替
child.stdin.as_mut()


@弗朗西斯·加涅解决了这个问题,非常感谢!
    {
        // Pass input file names via stdin
        let stdin: ChildStdin = child.stdin.take().unwrap();
        stdin.write_all("IMG_1709.CR2".as_bytes()).unwrap();
        // Leave scope:
        // "When an instance of ChildStdin is dropped, the ChildStdin’s underlying file handle will
        // be closed."
    }