← 中文资源

简体中文版本

给子进程写管道 stdin

Stdio::piped 接管子进程 stdin,写完缓冲区后写端随 drop 关闭:子进程读到 EOF 正常退出,wait_with_output 顺带收走标准输出。

阅读英文原文

实现说明

给子进程写管道 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));
}