]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/std_misc/process/pipe.md
New upstream version 1.25.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / std_misc / process / pipe.md
1 # Pipes
2
3 The `std::Child` struct represents a running child process, and exposes the
4 `stdin`, `stdout` and `stderr` handles for interaction with the underlying
5 process via pipes.
6
7 ```rust,ignore
8 use std::error::Error;
9 use std::io::prelude::*;
10 use std::process::{Command, Stdio};
11
12 static PANGRAM: &'static str =
13 "the quick brown fox jumped over the lazy dog\n";
14
15 fn main() {
16 // Spawn the `wc` command
17 let process = match Command::new("wc")
18 .stdin(Stdio::piped())
19 .stdout(Stdio::piped())
20 .spawn() {
21 Err(why) => panic!("couldn't spawn wc: {}", why.description()),
22 Ok(process) => process,
23 };
24
25 // Write a string to the `stdin` of `wc`.
26 //
27 // `stdin` has type `Option<ChildStdin>`, but since we know this instance
28 // must have one, we can directly `unwrap` it.
29 match process.stdin.unwrap().write_all(PANGRAM.as_bytes()) {
30 Err(why) => panic!("couldn't write to wc stdin: {}",
31 why.description()),
32 Ok(_) => println!("sent pangram to wc"),
33 }
34
35 // Because `stdin` does not live after the above calls, it is `drop`ed,
36 // and the pipe is closed.
37 //
38 // This is very important, otherwise `wc` wouldn't start processing the
39 // input we just sent.
40
41 // The `stdout` field also has type `Option<ChildStdout>` so must be unwrapped.
42 let mut s = String::new();
43 match process.stdout.unwrap().read_to_string(&mut s) {
44 Err(why) => panic!("couldn't read wc stdout: {}",
45 why.description()),
46 Ok(_) => print!("wc responded with:\n{}", s),
47 }
48 }
49 ```