# tokio::process::Child - Rust
API documentation for the Rust `Child` struct in crate `tokio`.
Keywords: rust, rustlang, rust-lang, Child

# Struct tokio::process::Child [−] [src]

    pub struct Child {
        pub stdin: Option<ChildStdin>,
        pub stdout: Option<ChildStdout>,
        pub stderr: Option<ChildStderr>,
        // some fields omitted
    }

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

### `impl Child` [src]

#### `pub fn id(&self) -> Option<u32>` [src]

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<()>` [src]

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<()>` [src]

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

#### `pub async fn wait(&mut self) -> Result<ExitStatus>` [src]

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;

    #[tokio::main]
    async fn main() {
        let mut child = Command::new("cat").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>>` [src]

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.

#### `pub async fn wait_with_output(self) -> Result<Output>` [src]

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

### `impl Debug for Child` [src]

#### `fn fmt(&self, f: &mut Formatter<'_>) -> Result` [src]

Formats the value using the given formatter. Read more

## Auto Trait Implementations

### `impl !RefUnwindSafe for Child` [src]

### `impl Send for Child` [src]

### `impl Sync for Child` [src]

### `impl Unpin for Child` [src]

### `impl !UnwindSafe for Child` [src]

## Blanket Implementations

### `impl<T> Any for T where
T: 'static + ?Sized,` [src]

#### `pub fn type_id(&self) -> TypeId` [src]

Gets the `TypeId` of `self`. Read more

### `impl<T> Borrow<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow(&self) -> &Tⓘ

### Notable traits for &'_ mut F

`impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;`
` [src]

Immutably borrows from an owned value. Read more

### `impl<T> BorrowMut<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow_mut(&mut self) -> &mut Tⓘ

### Notable traits for &'_ mut F

`impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;`
` [src]

Mutably borrows from an owned value. Read more

### `impl<T> From<T> for T` [src]

#### `pub fn from(t: T) -> T` [src]

Performs the conversion.

### `impl<T, U> Into<U> for T where
U: From<T>,` [src]

#### `pub fn into(self) -> U` [src]

Performs the conversion.

### `impl<T, U> TryFrom<U> for T where
U: Into<T>,` [src]

#### `type Error = Infallible`

The type returned in the event of a conversion error.

#### `pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>` [src]

Performs the conversion.

### `impl<T, U> TryInto<U> for T where
U: TryFrom<T>,` [src]

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

The type returned in the event of a conversion error.

#### `pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>` [src]

Performs the conversion.