pub struct Command { /* private fields */ }
Expand description

This structure mimics the API of std::process::Command found in the standard library, but replaces functions that create a process with an asynchronous variant. The main provided asynchronous functions are spawn, status, and output.

Command uses asynchronous versions of some std types (for example Child).

Implementations

Constructs a new Command for launching the program at path program, with the following default configuration:

  • No arguments to the program
  • Inherit the current process’s environment
  • Inherit the current process’s working directory
  • Inherit stdin/stdout/stderr for spawn or status, but create pipes for output

Builder methods are provided to change these defaults and otherwise configure the process.

If program is not an absolute path, the PATH will be searched in an OS-defined way.

The search path to be used may be controlled by setting the PATH environment variable on the Command, but this has some implementation limitations on Windows (see issue rust-lang/rust#37519).

Examples

Basic usage:

use tokio::process::Command;
let command = Command::new("sh");

Adds an argument to pass to the program.

Only one argument can be passed per use. So instead of:

tokio::process::Command::new("sh")
  .arg("-C /path/to/repo");

usage would be:

tokio::process::Command::new("sh")
  .arg("-C")
  .arg("/path/to/repo");

To pass multiple arguments see args.

Examples

Basic usage:

use tokio::process::Command;

let command = Command::new("ls")
        .arg("-l")
        .arg("-a");

Adds multiple arguments to pass to the program.

To pass a single argument see arg.

Examples

Basic usage:

use tokio::process::Command;

let command = Command::new("ls")
        .args(&["-l", "-a"]);

Inserts or updates an environment variable mapping.

Note that environment variable names are case-insensitive (but case-preserving) on Windows, and case-sensitive on all other platforms.

Examples

Basic usage:

use tokio::process::Command;

let command = Command::new("ls")
        .env("PATH", "/bin");

Adds or updates multiple environment variable mappings.

Examples

Basic usage:

use tokio::process::Command;
use std::process::{Stdio};
use std::env;
use std::collections::HashMap;

let filtered_env : HashMap<String, String> =
    env::vars().filter(|&(ref k, _)|
        k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
    ).collect();

let command = Command::new("printenv")
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .env_clear()
        .envs(&filtered_env);

Removes an environment variable mapping.

Examples

Basic usage:

use tokio::process::Command;

let command = Command::new("ls")
        .env_remove("PATH");

Clears the entire environment map for the child process.

Examples

Basic usage:

use tokio::process::Command;

let command = Command::new("ls")
        .env_clear();

Sets the working directory for the child process.

Platform-specific behavior

If the program path is relative (e.g., "./script.sh"), it’s ambiguous whether it should be interpreted relative to the parent’s working directory or relative to current_dir. The behavior in this case is platform specific and unstable, and it’s recommended to use canonicalize to get an absolute program path instead.

Examples

Basic usage:

use tokio::process::Command;

let command = Command::new("ls")
        .current_dir("/bin");

Sets configuration for the child process’s standard input (stdin) handle.

Defaults to inherit when used with spawn or status, and defaults to piped when used with output.

Examples

Basic usage:

use std::process::{Stdio};
use tokio::process::Command;

let command = Command::new("ls")
        .stdin(Stdio::null());

Sets configuration for the child process’s standard output (stdout) handle.

Defaults to inherit when used with spawn or status, and defaults to piped when used with output.

Examples

Basic usage:

use tokio::process::Command;;
use std::process::Stdio;

let command = Command::new("ls")
        .stdout(Stdio::null());

Sets configuration for the child process’s standard error (stderr) handle.

Defaults to inherit when used with spawn or status, and defaults to piped when used with output.

Examples

Basic usage:

use tokio::process::Command;;
use std::process::{Stdio};

let command = Command::new("ls")
        .stderr(Stdio::null());

Controls whether a kill operation should be invoked on a spawned child process when its corresponding Child handle is dropped.

By default, this value is assumed to be false, meaning the next spawned process will not be killed on drop, similar to the behavior of the standard library.

Sets the child process’s user ID. This translates to a setuid call in the child process. Failure in the setuid call will cause the spawn to fail.

Similar to uid but sets the group ID of the child process. This has the same semantics as the uid field.

Schedules a closure to be run just before the exec function is invoked.

The closure is allowed to return an I/O error whose OS error code will be communicated back to the parent and returned as an error from when the spawn was requested.

Multiple closures can be registered and they will be called in order of their registration. If a closure returns Err then no further closures will be called and the spawn operation will immediately return with a failure.

Safety

This closure will be run in the context of the child process after a fork. This primarily means that any modifications made to memory on behalf of this closure will not be visible to the parent process. This is often a very constrained environment where normal operations like malloc or acquiring a mutex are not guaranteed to work (due to other threads perhaps still running when the fork was run).

This also means that all resources such as file descriptors and memory-mapped regions got duplicated. It is your responsibility to make sure that the closure does not violate library invariants by making invalid use of these duplicates.

When this closure is run, aspects such as the stdio file descriptors and working directory have successfully been changed, so output to these locations may not appear where intended.

Executes the command as a child process, returning a handle to it.

By default, stdin, stdout and stderr are inherited from the parent.

This method will spawn the child process synchronously and return a handle to a future-aware child process. The Child returned implements Future itself to acquire the ExitStatus of the child, and otherwise the Child has methods to acquire handles to the stdin, stdout, and stderr streams.

All I/O this child does will be associated with the current default event loop.

Caveats

Similar to the behavior to the standard library, and unlike the futures paradigm of dropping-implies-cancellation, the 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.

Examples

Basic usage:

use tokio::process::Command;

async fn run_ls() -> std::process::ExitStatus {
    Command::new("ls")
        .spawn()
        .expect("ls command failed to start")
        .await
        .expect("ls command failed to run")
}

Executes the command as a child process, waiting for it to finish and collecting its exit status.

By default, stdin, stdout and stderr are inherited from the parent. If any input/output handles are set to a pipe then they will be immediately closed after the child is spawned.

All I/O this child does will be associated with the current default event loop.

If this future is dropped before the future resolves, then the child will be killed, if it was spawned.

Errors

This future will return an error if the child process cannot be spawned or if there is an error while awaiting its status.

Examples

Basic usage:

use tokio::process::Command;

async fn run_ls() -> std::process::ExitStatus {
    Command::new("ls")
        .status()
        .await
        .expect("ls command failed to run")
}

Executes the command as a child process, waiting for it to finish and collecting all of its output.

Note: this method, unlike the standard library, will unconditionally configure the stdout/stderr handles to be pipes, even if they have been previously configured. If this is not desired then the spawn method should be used in combination with the wait_with_output method on child.

This method will return a future representing the collection of the child process’s stdout/stderr. It will resolve to the Output type in the standard library, containing stdout and stderr as Vec<u8> along with an ExitStatus representing how the process exited.

All I/O this child does will be associated with the current default event loop.

If this future is dropped before the future resolves, then the child will be killed, if it was spawned.

Examples

Basic usage:

use tokio::process::Command;

async fn run_ls() {
    let output: std::process::Output = Command::new("ls")
        .output()
        .await
        .expect("ls command failed to run");
    println!("stderr of ls: {:?}", output.stderr);
}

Trait Implementations

Formats the value using the given formatter. Read more

Performs the conversion.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.