Command Reads Piped Stdin

Spawn a child with Stdio::piped stdin, write one buffer into its handle, then collect stdout after the write end drops and the child sees EOF.

RustCli Tooling

Code

rustsnippet
22 lines
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));
}

The mechanics

A compact reading: the function main, doing all the work.

Points of care

  • Zero packages pulled in — the runtime ships every API this code touches.

Using it

The entry-point signature is fn main()

Key statements

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");

Interactive Tools for This Topic

FAQ

How do you run Command Reads Piped Stdin?
The file is self-contained: run it directly, no dependencies to install beforehand.