Skip to content

Commit 8713d39

Browse files
authored
process: add example for reading Child stdout (#7141)
1 parent 7e27911 commit 8713d39

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

tokio/src/process/mod.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1169,6 +1169,8 @@ impl Child {
11691169
///
11701170
/// This is equivalent to sending a `SIGKILL` on unix platforms.
11711171
///
1172+
/// # Examples
1173+
///
11721174
/// If the child has to be killed remotely, it is possible to do it using
11731175
/// a combination of the select! macro and a `oneshot` channel. In the following
11741176
/// example, the child will run until completion unless a message is sent on
@@ -1190,6 +1192,46 @@ impl Child {
11901192
/// }
11911193
/// }
11921194
/// ```
1195+
///
1196+
/// You can also interact with the child's standard I/O. For example, you can
1197+
/// read its stdout while waiting for it to exit.
1198+
///
1199+
/// ```no_run
1200+
/// # use std::process::Stdio;
1201+
/// #
1202+
/// # use tokio::io::AsyncReadExt;
1203+
/// # use tokio::process::Command;
1204+
/// # use tokio::sync::oneshot::channel;
1205+
///
1206+
/// #[tokio::main]
1207+
/// async fn main() {
1208+
/// let (_tx, rx) = channel::<()>();
1209+
///
1210+
/// let mut child = Command::new("echo")
1211+
/// .arg("Hello World!")
1212+
/// .stdout(Stdio::piped())
1213+
/// .spawn()
1214+
/// .unwrap();
1215+
///
1216+
/// let mut stdout = child.stdout.take().expect("stdout is not captured");
1217+
///
1218+
/// let read_stdout = tokio::spawn(async move {
1219+
/// let mut buff = Vec::new();
1220+
/// let _ = stdout.read_to_end(&mut buff).await;
1221+
///
1222+
/// buff
1223+
/// });
1224+
///
1225+
/// tokio::select! {
1226+
/// _ = child.wait() => {}
1227+
/// _ = rx => { child.kill().await.expect("kill failed") },
1228+
/// }
1229+
///
1230+
/// let buff = read_stdout.await.unwrap();
1231+
///
1232+
/// assert_eq!(buff, b"Hello World!\n");
1233+
/// }
1234+
/// ```
11931235
pub async fn kill(&mut self) -> io::Result<()> {
11941236
self.start_kill()?;
11951237
self.wait().await?;

0 commit comments

Comments
 (0)