实现说明
给子进程写管道 stdin以函数 main为骨架。
常见问题
「给子进程写管道 stdin」这个示例怎么运行?
运行这个文件就行;脚本没有任何外部要求。
核心语句
let out = child.wait_with_output().expect("collect output");
let mut child = Command::new("cat")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("spawn cat");
.write_all(b"deploy notes\n")
.expect("write stdin");
代码示例
use std::io::Write;
use std::process::{Command, Stdio};
fn main() {
// spawn 子进程并接管它的 stdin:Stdio::piped() 返回写端句柄
let mut child = Command::new("cat")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("spawn cat");
// 写入缓冲区;写端在语句结束时 drop,子进程读到 EOF 后退出
child
.stdin
.take()
.expect("stdin piped")
.write_all(b"deploy notes\n")
.expect("write stdin");
let out = child.wait_with_output().expect("collect output");
print!("piped: {}", String::from_utf8_lossy(&out.stdout));
}