Rust Reference ยท Standard Library Modules
Rust Command type
Reference for std::process::Command: output, status and spawn, arguments and env, piping stdin and stdout, exit codes, NotFound errors and avoiding shell injection.
std::process::Command builds and runs an external program. You create it with the program name, add arguments, environment variables, a working directory and the wiring of the standard streams, and then run it in one of three ways: status() runs it and waits for the exit status, output() runs it and captures stdout and stderr, and spawn() starts it and gives you a Child handle to talk to while it runs.
Command does not use a shell. The program and each argument are passed to the operating system separately, so spaces, quotes and ; in an argument are just characters. That makes it much safer than building a command string, as long as you do not hand user input to sh -c yourself.
use std::process::Command; let out = Command::new("echo").arg("hi").output()?;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl Command { pub fn new<S: AsRef<OsStr>>(program: S) -> Command; pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command; pub fn args<I, S>(&mut self, args: I) -> &mut Command; pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command; pub fn env_clear(&mut self) -> &mut Command; pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command; pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command; pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command; // also stdout, stderr pub fn spawn(&mut self) -> io::Result<Child>; pub fn output(&mut self) -> io::Result<Output>; pub fn status(&mut self) -> io::Result<ExitStatus>; } impl Child { pub fn wait(&mut self) -> io::Result<ExitStatus>; pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>>; pub fn wait_with_output(self) -> io::Result<Output>; pub fn kill(&mut self) -> io::Result<()>; pub fn id(&self) -> u32; }
| Name | Description |
|---|---|
Stdio::inherit() |
Use the parent's stream. Default for status and spawn stdout/stderr. |
Stdio::piped() |
Create a pipe you can read or write via child.stdin, child.stdout, child.stderr. |
Stdio::null() |
Connect the stream to nothing. |
Output |
Struct with status, stdout: Vec<u8> and stderr: Vec<u8>. |
ExitStatus |
success(), code() -> Option<i32> (None when killed by a signal on Unix). |
Returns. output() and status() return Ok whenever the program ran, whatever its exit code. Check status.success() yourself. output() captures both streams by default; status() inherits them.
Errors and panics. Err means the program could not be started (NotFound, PermissionDenied) or that waiting failed. There are no panics. The Command builder's methods return &mut Command, so they chain, but storing the chain in a variable needs let mut cmd = Command::new(..).
Usage notes
- Zombie processes. A
Childthat is dropped withoutwait()is not killed and not reaped; on Unix it stays a zombie until your program exits. Always callwait,wait_with_outputorstatus. - Deadlocks with pipes. If you pipe both stdin and stdout and write a lot of input before reading, the child can block on a full output pipe. Write in a separate thread, or use
wait_with_outputafter closing stdin. - Close stdin. Programs like
catandtrstop only when their input ends. Drop the stdin handle. - Arguments are not shell-parsed.
arg("-l -a")is one argument with a space. Useargs(["-l", "-a"]). Wildcards like*are not expanded either. - Never build
sh -cstrings from user input. That is command injection. Pass user values as separate arguments. - Portability. Program names differ per OS (
diris a shell built-in on Windows). Usecfg!(windows)or avoid external tools where a Rust library will do. - Search path. A name without a slash is looked up in
PATH. Use a full path for predictable behavior. - Environment. The child inherits the parent's environment plus your
envchanges.env_clearstarts empty. - Replacing the process. On Unix,
std::os::unix::process::CommandExt::execreplaces the current process instead of forking. - Our runner has no network and a minimal system, so the examples use only basic tools such as
echo,trandwc. On your own machine any program works.