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

process: add example for reading Child stdout #7141

Merged
merged 4 commits into from
Feb 8, 2025
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
37 changes: 37 additions & 0 deletions tokio/src/process/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1169,6 +1169,8 @@ impl Child {
///
/// This is equivalent to sending a `SIGKILL` on unix platforms.
///
/// # Examples
///
/// If the child has to be killed remotely, it is possible to do it using
/// a combination of the select! macro and a `oneshot` channel. In the following
/// example, the child will run until completion unless a message is sent on
Expand All @@ -1190,6 +1192,41 @@ impl Child {
/// }
/// }
/// ```
///
/// You can also interact with the child's standard I/O. For example, you can
/// read its stdout while waiting for it to exit.
///
/// ```no_run
/// # use std::process::Stdio;
/// #
/// # use tokio::io::AsyncReadExt;
/// # use tokio::process::Command;
/// # use tokio::sync::oneshot::channel;
/// #
/// # use futures::future::join;
///
/// #[tokio::main]
/// async fn main() {
/// let (_tx, rx) = channel::<()>();
///
/// let mut child = Command::new("echo")
/// .arg("Hello World!")
/// .stdout(Stdio::piped())
/// .spawn()
/// .unwrap();
///
/// let mut stdout = child.stdout.take().expect("stdout is not captured");
/// let mut buff = Vec::new();
/// let wait_for_output = join(child.wait(), stdout.read_to_end(&mut buff));
///
/// tokio::select! {
/// _ = wait_for_output => {}
/// _ = rx => child.kill().await.expect("kill failed"),
/// }
///
/// assert_eq!(buff, b"Hello World!\n");
/// }
maminrayej marked this conversation as resolved.
Show resolved Hide resolved
/// ```
pub async fn kill(&mut self) -> io::Result<()> {
self.start_kill()?;
self.wait().await?;
Expand Down