pub struct KillGroupOnDrop(pub Child);Expand description
A child that, if dropped before it was reaped, takes its process group
with it (start_kill_child_and_group) rather than only itself, as
kill_on_drop does. For a CLI a caller may abandon (a cancelled task):
its helpers live in the CLI’s group and would otherwise outlive it. Derefs
to the child.
Tuple Fields§
§0: ChildMethods from Deref<Target = Child>§
pub fn id(&self) -> Option<u32>
pub fn id(&self) -> Option<u32>
Returns the OS-assigned process identifier associated with this child while it is still running.
Once the child has been polled to completion this will return None.
This is done to avoid confusion on platforms like Unix where the OS
identifier could be reused once the process has completed.
pub fn start_kill(&mut self) -> Result<(), Error>
pub fn start_kill(&mut self) -> Result<(), Error>
Attempts to force the child to exit, but does not wait for the request to take effect.
On Unix platforms, this is the equivalent to sending a SIGKILL. Note
that on Unix platforms it is possible for a zombie process to remain
after a kill is sent; to avoid this, the caller should ensure that either
child.wait().await or child.try_wait() is invoked successfully.
pub async fn kill(&mut self) -> Result<(), Error>
pub async fn kill(&mut self) -> Result<(), Error>
Forces the child to exit.
This is equivalent to sending a SIGKILL on unix platforms
followed by wait.
Note: std version of Child::kill does not wait.
For an equivalent of Child::kill in the standard library,
use start_kill.
§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
the oneshot channel. If that happens, the child is killed immediately
using the .kill() method.
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! {
_ = child.wait() => {}
_ = recv => child.kill().await.expect("kill failed"),
}
}You can also interact with the child’s standard I/O. For example, you can read its stdout while waiting for it to exit.
#[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 read_stdout = tokio::spawn(async move {
let mut buff = Vec::new();
let _ = stdout.read_to_end(&mut buff).await;
buff
});
tokio::select! {
_ = child.wait() => {}
_ = rx => { child.kill().await.expect("kill failed") },
}
let buff = read_stdout.await.unwrap();
assert_eq!(buff, b"Hello World!\n");
}pub async fn wait(&mut self) -> Result<ExitStatus, Error>
pub async fn wait(&mut self) -> Result<ExitStatus, Error>
Waits for the child to exit completely, returning the status that it exited with. This function will continue to have the same return value after it has been called at least once.
The stdin handle to the child process, if any, will be closed before waiting. This helps avoid deadlock: it ensures that the child does not block waiting for input from the parent, while the parent waits for the child to exit.
If the caller wishes to explicitly control when the child’s stdin
handle is closed, they may .take() it before calling .wait():
§Cancel safety
This function is cancel safe.
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use std::process::Stdio;
#[tokio::main]
async fn main() {
let mut child = Command::new("cat")
.stdin(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
tokio::spawn(async move {
// do something with stdin here...
stdin.write_all(b"hello world\n").await.unwrap();
// then drop when finished
drop(stdin);
});
// wait for the process to complete
let _ = child.wait().await;
}pub fn try_wait(&mut self) -> Result<Option<ExitStatus>, Error>
pub fn try_wait(&mut self) -> Result<Option<ExitStatus>, Error>
Attempts to collect the exit status of the child if it has already exited.
This function will not block the calling thread and will only check to see if the child process has exited or not. If the child has exited then on Unix the process ID is reaped. This function is guaranteed to repeatedly return a successful exit status so long as the child has already exited.
If the child has exited, then Ok(Some(status)) is returned. If the
exit status is not available at this time then Ok(None) is returned.
If an error occurs, then that error is returned.
Note that unlike wait, this function will not attempt to drop stdin,
nor will it wake the current task if the child exits.