Struct tokio::process::Child

source ·
pub struct Child {
    pub stdin: Option<ChildStdin>,
    pub stdout: Option<ChildStdout>,
    pub stderr: Option<ChildStderr>,
    /* private fields */
}
Expand description

Representation of a child process spawned onto an event loop.

Caveats

Similar to the behavior to the standard library, and unlike the futures paradigm of dropping-implies-cancellation, a spawned process will, by default, continue to execute even after the Child handle has been dropped.

The Command::kill_on_drop method can be used to modify this behavior and kill the child process if the Child wrapper is dropped before it has exited.

Fields§

§stdin: Option<ChildStdin>

The handle for writing to the child’s standard input (stdin), if it has been captured. To avoid partially moving the child and thus blocking yourself from calling functions on child while using stdin, you might find it helpful to do:

let stdin = child.stdin.take().unwrap();
§stdout: Option<ChildStdout>

The handle for reading from the child’s standard output (stdout), if it has been captured. You might find it helpful to do

let stdout = child.stdout.take().unwrap();

to avoid partially moving the child and thus blocking yourself from calling functions on child while using stdout.

§stderr: Option<ChildStderr>

The handle for reading from the child’s standard error (stderr), if it has been captured. You might find it helpful to do

let stderr = child.stderr.take().unwrap();

to avoid partially moving the child and thus blocking yourself from calling functions on child while using stderr.

Implementations§

source§

impl Child

source

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.

source

pub fn start_kill(&mut self) -> Result<()>

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.

source

pub async fn kill(&mut self) -> Result<()>

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.

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"),
    }
}
source

pub async fn wait(&mut self) -> Result<ExitStatus>

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():

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;
}
source

pub fn try_wait(&mut self) -> Result<Option<ExitStatus>>

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.

source

pub async fn wait_with_output(self) -> Result<Output>

Returns a future that will resolve to an Output, containing the exit status, stdout, and stderr of the child process.

The returned future will simultaneously waits for the child to exit and collect all remaining output on the stdout/stderr handles, returning an Output instance.

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.

By default, stdin, stdout and stderr are inherited from the parent. In order to capture the output into this Output it is necessary to create new pipes between parent and child. Use stdout(Stdio::piped()) or stderr(Stdio::piped()), respectively, when creating a Command.

Trait Implementations§

source§

impl Debug for Child

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Child

§

impl Send for Child

§

impl Sync for Child

§

impl Unpin for Child

§

impl !UnwindSafe for Child

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.