diff --git a/tokio/src/process/mod.rs b/tokio/src/process/mod.rs index e04a43510..4a070023b 100644 --- a/tokio/src/process/mod.rs +++ b/tokio/src/process/mod.rs @@ -766,6 +766,32 @@ impl Child { /// Forces the child to exit. /// /// This is equivalent to sending a SIGKILL on unix platforms. + /// + /// 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 + /// the oneshot channel. If that happens, the child is killed immediately + /// using the `.kill()` method. + /// + /// ```no_run + /// use tokio::process::Command; + /// use tokio::sync::oneshot::channel; + /// + /// #[tokio::main] + /// async fn main() { + /// let (send, recv) = channel::<()>(); + /// let mut child = Command::new("sleep").arg("1").spawn().unwrap(); + /// tokio::spawn(async move { send.send(()) }); + /// tokio::select! { + /// _ = &mut child => {} + /// _ = recv => { + /// &mut child.kill(); + /// // NB: await the child here to avoid a zombie process on Unix platforms + /// child.await.unwrap(); + /// } + /// } + /// } + pub fn kill(&mut self) -> io::Result<()> { self.child.kill() }