Skip to content

Commit 46691a5

Browse files
authored
Rollup merge of #40122 - robinst:process-add-example-for-writing-to-stdin, r=alexcrichton
Example for how to provide stdin using std::process::Command Spawning a child process and writing to its stdin is a bit tricky due to `as_mut` and having to use a limited borrow. An example for this might help newer users. r? @steveklabnik
2 parents 8ca232f + 8079bf3 commit 46691a5

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/libstd/process.rs

+25
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,31 @@
2727
//!
2828
//! assert!(ecode.success());
2929
//! ```
30+
//!
31+
//! Calling a command with input and reading its output:
32+
//!
33+
//! ```no_run
34+
//! use std::process::{Command, Stdio};
35+
//! use std::io::Write;
36+
//!
37+
//! let mut child = Command::new("/bin/cat")
38+
//! .stdin(Stdio::piped())
39+
//! .stdout(Stdio::piped())
40+
//! .spawn()
41+
//! .expect("failed to execute child");
42+
//!
43+
//! {
44+
//! // limited borrow of stdin
45+
//! let stdin = child.stdin.as_mut().expect("failed to get stdin");
46+
//! stdin.write_all(b"test").expect("failed to write to stdin");
47+
//! }
48+
//!
49+
//! let output = child
50+
//! .wait_with_output()
51+
//! .expect("failed to wait on child");
52+
//!
53+
//! assert_eq!(b"test", output.stdout.as_slice());
54+
//! ```
3055
3156
#![stable(feature = "process", since = "1.0.0")]
3257

0 commit comments

Comments
 (0)