Struct Command
struct Command { ... }
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
impl Command
fn new<S: AsRef<OsStr>>(program: S) -> CommandConstructs a new
Commandfor launching the program at pathprogram, 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
spawnorstatus, but create pipes foroutput
Builder methods are provided to change these defaults and otherwise configure the process.
If
programis not an absolute path, thePATHwill be searched in an OS-defined way.The search path to be used may be controlled by setting the
PATHenvironment 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 mut command = Command::new("sh"); # let _ = command.output(); // assert borrow checkerfn as_std(self: &Self) -> &StdCommandCheaply convert to a
&std::process::Commandfor places where the type from the standard library is expected.fn as_std_mut(self: &mut Self) -> &mut StdCommandCheaply convert to a
&mut std::process::Commandfor places where the type from the standard library is expected.fn into_std(self: Self) -> StdCommandCheaply convert into a
std::process::Command.Note that Tokio specific options will be lost. Currently, this only applies to
kill_on_drop.fn arg<S: AsRef<OsStr>>(self: &mut Self, arg: S) -> &mut CommandAdds an argument to pass to the program.
Only one argument can be passed per use. So instead of:
let mut command = tokio::process::Command::new("sh"); command.arg("-C /path/to/repo"); # let _ = command.output(); // assert borrow checkerusage would be:
let mut command = tokio::process::Command::new("sh"); command.arg("-C"); command.arg("/path/to/repo"); # let _ = command.output(); // assert borrow checkerTo pass multiple arguments see
args.Examples
Basic usage:
# async fn test() { // allow using await use tokio::process::Command; let output = Command::new("ls") .arg("-l") .arg("-a") .output().await.unwrap(); # }fn args<I, S>(self: &mut Self, args: I) -> &mut Command where I: IntoIterator<Item = S>, S: AsRef<OsStr>Adds multiple arguments to pass to the program.
To pass a single argument see
arg.Examples
Basic usage:
# async fn test() { // allow using await use tokio::process::Command; let output = Command::new("ls") .args(&["-l", "-a"]) .output().await.unwrap(); # }fn env<K, V>(self: &mut Self, key: K, val: V) -> &mut Command where K: AsRef<OsStr>, V: AsRef<OsStr>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:
# async fn test() { // allow using await use tokio::process::Command; let output = Command::new("ls") .env("PATH", "/bin") .output().await.unwrap(); # }fn envs<I, K, V>(self: &mut Self, vars: I) -> &mut Command where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>Adds or updates multiple environment variable mappings.
Examples
Basic usage:
# async fn test() { // allow using await 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 output = Command::new("printenv") .stdin(Stdio::null()) .stdout(Stdio::inherit()) .env_clear() .envs(&filtered_env) .output().await.unwrap(); # }fn env_remove<K: AsRef<OsStr>>(self: &mut Self, key: K) -> &mut CommandRemoves an environment variable mapping.
Examples
Basic usage:
# async fn test() { // allow using await use tokio::process::Command; let output = Command::new("ls") .env_remove("PATH") .output().await.unwrap(); # }fn env_clear(self: &mut Self) -> &mut CommandClears the entire environment map for the child process.
Examples
Basic usage:
# async fn test() { // allow using await use tokio::process::Command; let output = Command::new("ls") .env_clear() .output().await.unwrap(); # }fn current_dir<P: AsRef<Path>>(self: &mut Self, dir: P) -> &mut CommandSets 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 tocurrent_dir. The behavior in this case is platform specific and unstable, and it's recommended to usecanonicalizeto get an absolute program path instead.Examples
Basic usage:
# async fn test() { // allow using await use tokio::process::Command; let output = Command::new("ls") .current_dir("/bin") .output().await.unwrap(); # }fn stdin<T: Into<Stdio>>(self: &mut Self, cfg: T) -> &mut CommandSets configuration for the child process's standard input (stdin) handle.
Defaults to
inherit.Examples
Basic usage:
# async fn test() { // allow using await use std::process::{Stdio}; use tokio::process::Command; let output = Command::new("ls") .stdin(Stdio::null()) .output().await.unwrap(); # }fn stdout<T: Into<Stdio>>(self: &mut Self, cfg: T) -> &mut CommandSets configuration for the child process's standard output (stdout) handle.
Defaults to
inheritwhen used withspawnorstatus, and defaults topipedwhen used withoutput.Examples
Basic usage:
# async fn test() { // allow using await use tokio::process::Command; use std::process::Stdio; let output = Command::new("ls") .stdout(Stdio::null()) .output().await.unwrap(); # }fn stderr<T: Into<Stdio>>(self: &mut Self, cfg: T) -> &mut CommandSets configuration for the child process's standard error (stderr) handle.
Defaults to
inheritwhen used withspawnorstatus, and defaults topipedwhen used withoutput.Examples
Basic usage:
# async fn test() { // allow using await use tokio::process::Command; use std::process::{Stdio}; let output = Command::new("ls") .stderr(Stdio::null()) .output().await.unwrap(); # }fn kill_on_drop(self: &mut Self, kill_on_drop: bool) -> &mut CommandControls whether a
killoperation should be invoked on a spawned child process when its correspondingChildhandle 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.Caveats
On Unix platforms processes must be "reaped" by their parent process after they have exited in order to release all OS resources. A child process which has exited, but has not yet been reaped by its parent is considered a "zombie" process. Such processes continue to count against limits imposed by the system, and having too many zombie processes present can prevent additional processes from being spawned.
Although issuing a
killsignal to the child process is a synchronous operation, the resulting zombie process cannot be.awaited inside of the destructor to avoid blocking other tasks. The tokio runtime will, on a best-effort basis, attempt to reap and clean up such processes in the background, but no additional guarantees are made with regard to how quickly or how often this procedure will take place.If stronger guarantees are required, it is recommended to avoid dropping a
Childhandle where possible, and instead utilizechild.wait().awaitorchild.kill().awaitwhere possible.fn uid(self: &mut Self, id: u32) -> &mut CommandSets the child process's user ID. This translates to a
setuidcall in the child process. Failure in thesetuidcall will cause the spawn to fail.fn gid(self: &mut Self, id: u32) -> &mut CommandSimilar to
uidbut sets the group ID of the child process. This has the same semantics as theuidfield.fn arg0<S>(self: &mut Self, arg: S) -> &mut Command where S: AsRef<OsStr>Sets executable argument.
Set the first process argument,
argv[0], to something other than the default executable path.unsafe fn pre_exec<F>(self: &mut Self, f: F) -> &mut Command where F: FnMut() -> io::Result<()> + Send + Sync + 'staticSchedules a closure to be run just before the
execfunction 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
Errthen 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 likemallocor acquiring a mutex are not guaranteed to work (due to other threads perhaps still running when theforkwas 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.
fn process_group(self: &mut Self, pgroup: i32) -> &mut CommandSets the process group ID (PGID) of the child process. Equivalent to a
setpgidcall in the child process, but may be more efficient.Process groups determine which processes receive signals.
Examples
Pressing Ctrl-C in a terminal will send
SIGINTto all processes in the current foreground process group. By spawning thesleepsubprocess in a new process group, it will not receiveSIGINTfrom the terminal.The parent process could install a signal handler and manage the process on its own terms.
A process group ID of 0 will use the process ID as the PGID.
# async fn test() { // allow using await use tokio::process::Command; let output = Command::new("sleep") .arg("10") .process_group(0) .output() .await .unwrap(); # }fn spawn(self: &mut Self) -> io::Result<Child>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
Childreturned implementsFutureitself to acquire theExitStatusof the child, and otherwise theChildhas 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.
Examples
Basic usage:
use tokio::process::Command; async fn run_ls() -> std::process::ExitStatus { Command::new("ls") .spawn() .expect("ls command failed to start") .wait() .await .expect("ls command failed to run") }Caveats
Dropping/Cancellation
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
Childhandle has been dropped.The
Command::kill_on_dropmethod can be used to modify this behavior and kill the child process if theChildwrapper is dropped before it has exited.Unix Processes
On Unix platforms processes must be "reaped" by their parent process after they have exited in order to release all OS resources. A child process which has exited, but has not yet been reaped by its parent is considered a "zombie" process. Such processes continue to count against limits imposed by the system, and having too many zombie processes present can prevent additional processes from being spawned.
The tokio runtime will, on a best-effort basis, attempt to reap and clean up any process which it has spawned. No additional guarantees are made with regard to how quickly or how often this procedure will take place.
It is recommended to avoid dropping a
Childprocess handle before it has been fullyawaited if stricter cleanup guarantees are required.Errors
On Unix platforms this method will fail with
std::io::ErrorKind::WouldBlockif the system process limit is reached (which includes other applications running on the system).fn status(self: &mut Self) -> impl Future<Output = io::Result<ExitStatus>>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.
The destructor of the future returned by this function will kill the child if
kill_on_dropis set to true.Errors
This future will return an error if the child process cannot be spawned or if there is an error while awaiting its status.
On Unix platforms this method will fail with
std::io::ErrorKind::WouldBlockif the system process limit is reached (which includes other applications running on the system).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") }fn output(self: &mut Self) -> impl Future<Output = io::Result<Output>>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
spawnmethod should be used in combination with thewait_with_outputmethod on child.This method will return a future representing the collection of the child process's stdout/stderr. It will resolve to the
Outputtype in the standard library, containingstdoutandstderrasVec<u8>along with anExitStatusrepresenting how the process exited.All I/O this child does will be associated with the current default event loop.
The destructor of the future returned by this function will kill the child if
kill_on_dropis set to true.Errors
This future will return an error if the child process cannot be spawned or if there is an error while awaiting its status.
On Unix platforms this method will fail with
std::io::ErrorKind::WouldBlockif the system process limit is reached (which includes other applications running on the system).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); }fn get_kill_on_drop(self: &Self) -> boolReturns the boolean value that was previously set by
Command::kill_on_drop.Note that if you have not previously called
Command::kill_on_drop, the default value offalsewill be returned here.Examples
use Command; let mut cmd = new; assert!; cmd.kill_on_drop; assert!;
impl Debug for Command
fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<'_>) -> $crate::fmt::Result
impl Freeze for Command
impl From for Command
fn from(std: StdCommand) -> Command
impl RefUnwindSafe for Command
impl Send for Command
impl Sync for Command
impl Unpin for Command
impl UnwindSafe for Command
impl<T> Any for Command
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Command
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Command
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for Command
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for Command
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Command
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Command
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>