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.
Code
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
Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- How do you run Command Reads Piped Stdin?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.