Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: Created a simple example for tokio::process::ChildStdin #4479

Merged
merged 3 commits into from
Feb 12, 2022
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions tokio/src/process/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,54 @@
//! }
//! ```
//!
//! Here is another example using `sort` writing into the child process
//! standard input, capturing the output of the sorted text.
//!
//! ```no_run
//! use tokio::io::AsyncWriteExt;
//! use tokio::process::Command;
//!
//! use std::process::Stdio;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut cmd = Command::new("sort");
//!
//! // Specifying that we want pipe both the output and the input.
//! // Similarily to capturing the output, by configuring the pipe
//! // to stdin it can now be used as an asynchronous writer.
//! cmd.stdout(Stdio::piped());
//! cmd.stdin(Stdio::piped());
//!
//! let mut child = cmd.spawn().expect("failed to spawn command");
//!
//! // These are the animals we want to sort
//! let animals: &[&str] = &["dog", "bird", "frog", "cat", "fish"];
//!
//! let mut stdin = child
//! .stdin
//! .take()
//! .expect("child did not have a handle to stdin");
//!
//! // Write our animals to the child process
coral marked this conversation as resolved.
Show resolved Hide resolved
//! stdin
//! .write(animals.join("\n").as_bytes())
//! .await
//! .expect("could not write to stdin");
//!
//! // We drop the handle here which signals EOF to the child process.
//! // This tells the child process that it there is no more data on the pipe.
//! drop(stdin);
//!
//! let op = child.wait_with_output().await?;
//!
//! // Results should come back in sorted order
//! assert_eq!(op.stdout, "bird\ncat\ndog\nfish\nfrog\n".as_bytes());
//!
//! Ok(())
//! }
//! ```
//!
//! With some coordination, we can also pipe the output of one command into
//! another.
//!
Expand Down