Child

Struct Child 

1.0.0 ยท Source
pub struct Child {
    pub stdin: Option<ChildStdin>,
    pub stdout: Option<ChildStdout>,
    pub stderr: Option<ChildStderr>,
    /* private fields */
}
Expand description

Representation of a running or exited child process.

This structure is used to represent and manage child processes. A child process is created via the Command struct, which configures the spawning process and can itself be constructed using a builder-style interface.

There is no implementation of Drop for child processes, so if you do not ensure the Child has exited then it will continue to run, even after the Child handle to the child process has gone out of scope.

Calling wait (or other functions that wrap around it) will make the parent process wait until the child has actually exited before continuing.

ยงWarning

On some systems, calling wait or similar is necessary for the OS to release resources. A process that terminated but has not been waited on is still around as a โ€œzombieโ€. Leaving too many zombies around may exhaust global resources (for example process IDs).

The standard library does not automatically wait on child processes (not even if the Child is dropped), it is up to the application developer to do so. As a consequence, dropping Child handles without waiting on them first is not recommended in long-running applications.

ยงExamples

โ“˜
use std::process::Command;

let mut child = Command::new("/bin/cat")
    .arg("file.txt")
    .spawn()
    .expect("failed to execute child");

let ecode = child.wait().expect("failed to wait on child");

assert!(ecode.success());

Fieldsยง

ยงstdin: Option<ChildStdin>

The handle for writing to the childโ€™s standard input (stdin), if it has been captured. You might find it helpful to do

โ“˜
let stdin = child.stdin.take().expect("handle present");

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

ยง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().expect("handle present");

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().expect("handle present");

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

Implementationsยง

Sourceยง

impl Child

1.0.0 ยท Source

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

Forces the child process to exit. If the child has already exited, Ok(()) is returned.

The mapping to ErrorKinds is not part of the compatibility contract of the function.

This is equivalent to sending a SIGKILL on Unix platforms.

ยงExamples
use std::process::Command;

let mut command = Command::new("yes");
if let Ok(mut child) = command.spawn() {
    child.kill().expect("command couldn't be killed");
} else {
    println!("yes command didn't start");
}
1.3.0 ยท Source

pub fn id(&self) -> u32

Returns the OS-assigned process identifier associated with this child.

ยงExamples
use std::process::Command;

let mut command = Command::new("ls");
if let Ok(child) = command.spawn() {
    println!("Child's ID is {}", child.id());
} else {
    println!("ls command didn't start");
}
1.0.0 ยท Source

pub 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.

ยงExamples
use std::process::Command;

let mut command = Command::new("ls");
if let Ok(mut child) = command.spawn() {
    child.wait().expect("command wasn't running");
    println!("Child has finished its execution!");
} else {
    println!("ls command didn't start");
}
1.18.0 ยท 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.

ยงExamples
use std::process::Command;

let mut child = Command::new("ls").spawn()?;

match child.try_wait() {
    Ok(Some(status)) => println!("exited with: {status}"),
    Ok(None) => {
        println!("status not ready yet, let's really wait");
        let res = child.wait();
        println!("result: {res:?}");
    }
    Err(e) => println!("error attempting to wait: {e}"),
}
1.0.0 ยท Source

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

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 Result<Output> it is necessary to create new pipes between parent and child. Use stdout(Stdio::piped()) or stderr(Stdio::piped()), respectively.

ยงExamples
โ“˜
use std::process::{Command, Stdio};

let child = Command::new("/bin/cat")
    .arg("file.txt")
    .stdout(Stdio::piped())
    .spawn()
    .expect("failed to execute child");

let output = child
    .wait_with_output()
    .expect("failed to wait on child");

assert!(output.status.success());

Trait Implementationsยง

1.63.0 ยท Sourceยง

impl AsHandle for Child

Available on Windows only.
Sourceยง

fn as_handle(&self) -> BorrowedHandle<'_>

Borrows the handle. Read more
1.2.0 ยท Sourceยง

impl AsRawHandle for Child

Available on Windows only.
Sourceยง

fn as_raw_handle(&self) -> RawHandle

Extracts the raw handle. Read more
Sourceยง

impl ChildExt for Child

Available on Unix only.
Sourceยง

fn send_signal(&self, signal: i32) -> Result<()>

๐Ÿ”ฌThis is a nightly-only experimental API. (unix_send_signal #141975)
Sends a signal to a child process. Read more
Sourceยง

impl ChildExt for Child

Available on Windows only.
Sourceยง

fn main_thread_handle(&self) -> BorrowedHandle<'_>

๐Ÿ”ฌThis is a nightly-only experimental API. (windows_process_extensions_main_thread_handle #96723)
Extracts the main thread raw handle, without taking ownership
Sourceยง

impl ChildExt for Child

Available on Linux only.
Sourceยง

fn pidfd(&self) -> Result<&PidFd>

๐Ÿ”ฌThis is a nightly-only experimental API. (linux_pidfd #82971)
Obtains a reference to the PidFd created for this Child, if available. Read more
Sourceยง

fn into_pidfd(self) -> Result<PidFd, Self>

๐Ÿ”ฌThis is a nightly-only experimental API. (linux_pidfd #82971)
Returns the PidFd created for this Child, if available. Otherwise self is returned. Read more
1.16.0 ยท Sourceยง

impl Debug for Child

Sourceยง

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

Formats the value using the given formatter. Read more
1.63.0 ยท Sourceยง

impl From<Child> for OwnedHandle

Available on Windows only.
Sourceยง

fn from(child: Child) -> OwnedHandle

Takes ownership of a Childโ€™s process handle.

1.4.0 ยท Sourceยง

impl IntoRawHandle for Child

Available on Windows only.
Sourceยง

fn into_raw_handle(self) -> RawHandle

Consumes this object, returning the raw underlying handle. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

Sourceยง

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

Sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Sourceยง

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

Sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Sourceยง

impl<T> BorrowMut<T> for T
where 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 T
where 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 T
where U: Into<T>,

Sourceยง

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 T
where U: TryFrom<T>,

Sourceยง

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.