1 //! A module for working with processes.
3 //! This module is mostly concerned with spawning and interacting with child
4 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
7 //! # Spawning a process
9 //! The [`Command`] struct is used to configure and spawn processes:
12 //! use std::process::Command;
14 //! let output = Command::new("echo")
15 //! .arg("Hello world")
17 //! .expect("Failed to execute command");
19 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
22 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
23 //! to spawn a process. In particular, [`output`] spawns the child process and
24 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
25 //! that represents the spawned child process.
29 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
30 //! configured by passing an [`Stdio`] to the corresponding method on
31 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
32 //! example, piping output from one command into another command can be done
36 //! use std::process::{Command, Stdio};
38 //! // stdout must be configured with `Stdio::piped` in order to use
39 //! // `echo_child.stdout`
40 //! let echo_child = Command::new("echo")
41 //! .arg("Oh no, a tpyo!")
42 //! .stdout(Stdio::piped())
44 //! .expect("Failed to start echo process");
46 //! // Note that `echo_child` is moved here, but we won't be needing
47 //! // `echo_child` anymore
48 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
50 //! let mut sed_child = Command::new("sed")
51 //! .arg("s/tpyo/typo/")
52 //! .stdin(Stdio::from(echo_out))
53 //! .stdout(Stdio::piped())
55 //! .expect("Failed to start sed process");
57 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
58 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
61 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
62 //! [`ChildStdin`] implements [`Write`]:
65 //! use std::process::{Command, Stdio};
66 //! use std::io::Write;
68 //! let mut child = Command::new("/bin/cat")
69 //! .stdin(Stdio::piped())
70 //! .stdout(Stdio::piped())
72 //! .expect("failed to execute child");
75 //! // limited borrow of stdin
76 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
77 //! stdin.write_all(b"test").expect("failed to write to stdin");
80 //! let output = child
81 //! .wait_with_output()
82 //! .expect("failed to wait on child");
84 //! assert_eq!(b"test", output.stdout.as_slice());
87 //! [`spawn`]: Command::spawn
88 //! [`output`]: Command::output
90 //! [`stdout`]: Command::stdout
91 //! [`stdin`]: Command::stdin
92 //! [`stderr`]: Command::stderr
94 //! [`Write`]: io::Write
95 //! [`Read`]: io::Read
97 #![stable(feature = "process", since = "1.0.0")]
98 #![deny(unsafe_op_in_unsafe_fn)]
100 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
103 use crate::io::prelude::*;
105 use crate::ffi::OsStr;
108 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
109 use crate::path::Path;
111 use crate::sys::pipe::{read2, AnonPipe};
112 use crate::sys::process as imp;
113 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
115 /// Representation of a running or exited child process.
117 /// This structure is used to represent and manage child processes. A child
118 /// process is created via the [`Command`] struct, which configures the
119 /// spawning process and can itself be constructed using a builder-style
122 /// There is no implementation of [`Drop`] for child processes,
123 /// so if you do not ensure the `Child` has exited then it will continue to
124 /// run, even after the `Child` handle to the child process has gone out of
127 /// Calling [`wait`] (or other functions that wrap around it) will make
128 /// the parent process wait until the child has actually exited before
133 /// On some systems, calling [`wait`] or similar is necessary for the OS to
134 /// release resources. A process that terminated but has not been waited on is
135 /// still around as a "zombie". Leaving too many zombies around may exhaust
136 /// global resources (for example process IDs).
138 /// The standard library does *not* automatically wait on child processes (not
139 /// even if the `Child` is dropped), it is up to the application developer to do
140 /// so. As a consequence, dropping `Child` handles without waiting on them first
141 /// is not recommended in long-running applications.
146 /// use std::process::Command;
148 /// let mut child = Command::new("/bin/cat")
151 /// .expect("failed to execute child");
153 /// let ecode = child.wait()
154 /// .expect("failed to wait on child");
156 /// assert!(ecode.success());
159 /// [`wait`]: Child::wait
160 #[stable(feature = "process", since = "1.0.0")]
162 handle: imp::Process,
164 /// The handle for writing to the child's standard input (stdin), if it has
165 /// been captured. To avoid partially moving
166 /// the `child` and thus blocking yourself from calling
167 /// functions on `child` while using `stdin`,
168 /// you might find it helpful:
170 /// ```compile_fail,E0425
171 /// let stdin = child.stdin.take().unwrap();
173 #[stable(feature = "process", since = "1.0.0")]
174 pub stdin: Option<ChildStdin>,
176 /// The handle for reading from the child's standard output (stdout), if it
177 /// has been captured. You might find it helpful to do
179 /// ```compile_fail,E0425
180 /// let stdout = child.stdout.take().unwrap();
183 /// to avoid partially moving the `child` and thus blocking yourself from calling
184 /// functions on `child` while using `stdout`.
185 #[stable(feature = "process", since = "1.0.0")]
186 pub stdout: Option<ChildStdout>,
188 /// The handle for reading from the child's standard error (stderr), if it
189 /// has been captured. You might find it helpful to do
191 /// ```compile_fail,E0425
192 /// let stderr = child.stderr.take().unwrap();
195 /// to avoid partially moving the `child` and thus blocking yourself from calling
196 /// functions on `child` while using `stderr`.
197 #[stable(feature = "process", since = "1.0.0")]
198 pub stderr: Option<ChildStderr>,
201 impl AsInner<imp::Process> for Child {
202 fn as_inner(&self) -> &imp::Process {
207 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
208 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
211 stdin: io.stdin.map(ChildStdin::from_inner),
212 stdout: io.stdout.map(ChildStdout::from_inner),
213 stderr: io.stderr.map(ChildStderr::from_inner),
218 impl IntoInner<imp::Process> for Child {
219 fn into_inner(self) -> imp::Process {
224 #[stable(feature = "std_debug", since = "1.16.0")]
225 impl fmt::Debug for Child {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.debug_struct("Child")
228 .field("stdin", &self.stdin)
229 .field("stdout", &self.stdout)
230 .field("stderr", &self.stderr)
235 /// A handle to a child process's standard input (stdin).
237 /// This struct is used in the [`stdin`] field on [`Child`].
239 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
240 /// file handle will be closed. If the child process was blocked on input prior
241 /// to being dropped, it will become unblocked after dropping.
243 /// [`stdin`]: Child::stdin
245 #[stable(feature = "process", since = "1.0.0")]
246 pub struct ChildStdin {
250 #[stable(feature = "process", since = "1.0.0")]
251 impl Write for ChildStdin {
252 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
253 self.inner.write(buf)
256 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
257 self.inner.write_vectored(bufs)
260 fn is_write_vectored(&self) -> bool {
261 self.inner.is_write_vectored()
264 fn flush(&mut self) -> io::Result<()> {
269 impl AsInner<AnonPipe> for ChildStdin {
270 fn as_inner(&self) -> &AnonPipe {
275 impl IntoInner<AnonPipe> for ChildStdin {
276 fn into_inner(self) -> AnonPipe {
281 impl FromInner<AnonPipe> for ChildStdin {
282 fn from_inner(pipe: AnonPipe) -> ChildStdin {
283 ChildStdin { inner: pipe }
287 #[stable(feature = "std_debug", since = "1.16.0")]
288 impl fmt::Debug for ChildStdin {
289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290 f.pad("ChildStdin { .. }")
294 /// A handle to a child process's standard output (stdout).
296 /// This struct is used in the [`stdout`] field on [`Child`].
298 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
299 /// underlying file handle will be closed.
301 /// [`stdout`]: Child::stdout
303 #[stable(feature = "process", since = "1.0.0")]
304 pub struct ChildStdout {
308 #[stable(feature = "process", since = "1.0.0")]
309 impl Read for ChildStdout {
310 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
314 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
315 self.inner.read_vectored(bufs)
319 fn is_read_vectored(&self) -> bool {
320 self.inner.is_read_vectored()
324 unsafe fn initializer(&self) -> Initializer {
325 // SAFETY: Read is guaranteed to work on uninitialized memory
326 unsafe { Initializer::nop() }
330 impl AsInner<AnonPipe> for ChildStdout {
331 fn as_inner(&self) -> &AnonPipe {
336 impl IntoInner<AnonPipe> for ChildStdout {
337 fn into_inner(self) -> AnonPipe {
342 impl FromInner<AnonPipe> for ChildStdout {
343 fn from_inner(pipe: AnonPipe) -> ChildStdout {
344 ChildStdout { inner: pipe }
348 #[stable(feature = "std_debug", since = "1.16.0")]
349 impl fmt::Debug for ChildStdout {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 f.pad("ChildStdout { .. }")
355 /// A handle to a child process's stderr.
357 /// This struct is used in the [`stderr`] field on [`Child`].
359 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
360 /// underlying file handle will be closed.
362 /// [`stderr`]: Child::stderr
364 #[stable(feature = "process", since = "1.0.0")]
365 pub struct ChildStderr {
369 #[stable(feature = "process", since = "1.0.0")]
370 impl Read for ChildStderr {
371 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
375 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
376 self.inner.read_vectored(bufs)
380 fn is_read_vectored(&self) -> bool {
381 self.inner.is_read_vectored()
385 unsafe fn initializer(&self) -> Initializer {
386 // SAFETY: Read is guaranteed to work on uninitialized memory
387 unsafe { Initializer::nop() }
391 impl AsInner<AnonPipe> for ChildStderr {
392 fn as_inner(&self) -> &AnonPipe {
397 impl IntoInner<AnonPipe> for ChildStderr {
398 fn into_inner(self) -> AnonPipe {
403 impl FromInner<AnonPipe> for ChildStderr {
404 fn from_inner(pipe: AnonPipe) -> ChildStderr {
405 ChildStderr { inner: pipe }
409 #[stable(feature = "std_debug", since = "1.16.0")]
410 impl fmt::Debug for ChildStderr {
411 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412 f.pad("ChildStderr { .. }")
416 /// A process builder, providing fine-grained control
417 /// over how a new process should be spawned.
419 /// A default configuration can be
420 /// generated using `Command::new(program)`, where `program` gives a path to the
421 /// program to be executed. Additional builder methods allow the configuration
422 /// to be changed (for example, by adding arguments) prior to spawning:
425 /// use std::process::Command;
427 /// let output = if cfg!(target_os = "windows") {
428 /// Command::new("cmd")
429 /// .args(&["/C", "echo hello"])
431 /// .expect("failed to execute process")
433 /// Command::new("sh")
435 /// .arg("echo hello")
437 /// .expect("failed to execute process")
440 /// let hello = output.stdout;
443 /// `Command` can be reused to spawn multiple processes. The builder methods
444 /// change the command without needing to immediately spawn the process.
447 /// use std::process::Command;
449 /// let mut echo_hello = Command::new("sh");
450 /// echo_hello.arg("-c")
451 /// .arg("echo hello");
452 /// let hello_1 = echo_hello.output().expect("failed to execute process");
453 /// let hello_2 = echo_hello.output().expect("failed to execute process");
456 /// Similarly, you can call builder methods after spawning a process and then
457 /// spawn a new process with the modified settings.
460 /// use std::process::Command;
462 /// let mut list_dir = Command::new("ls");
464 /// // Execute `ls` in the current directory of the program.
465 /// list_dir.status().expect("process failed to execute");
469 /// // Change `ls` to execute in the root directory.
470 /// list_dir.current_dir("/");
472 /// // And then execute `ls` again but in the root directory.
473 /// list_dir.status().expect("process failed to execute");
475 #[stable(feature = "process", since = "1.0.0")]
481 /// Constructs a new `Command` for launching the program at
482 /// path `program`, with the following default configuration:
484 /// * No arguments to the program
485 /// * Inherit the current process's environment
486 /// * Inherit the current process's working directory
487 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
489 /// Builder methods are provided to change these defaults and
490 /// otherwise configure the process.
492 /// If `program` is not an absolute path, the `PATH` will be searched in
493 /// an OS-defined way.
495 /// The search path to be used may be controlled by setting the
496 /// `PATH` environment variable on the Command,
497 /// but this has some implementation limitations on Windows
498 /// (see issue #37519).
505 /// use std::process::Command;
507 /// Command::new("sh")
509 /// .expect("sh command failed to start");
511 #[stable(feature = "process", since = "1.0.0")]
512 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
513 Command { inner: imp::Command::new(program.as_ref()) }
516 /// Adds an argument to pass to the program.
518 /// Only one argument can be passed per use. So instead of:
521 /// # std::process::Command::new("sh")
522 /// .arg("-C /path/to/repo")
529 /// # std::process::Command::new("sh")
531 /// .arg("/path/to/repo")
535 /// To pass multiple arguments see [`args`].
537 /// [`args`]: Command::args
544 /// use std::process::Command;
546 /// Command::new("ls")
550 /// .expect("ls command failed to start");
552 #[stable(feature = "process", since = "1.0.0")]
553 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
554 self.inner.arg(arg.as_ref());
558 /// Adds multiple arguments to pass to the program.
560 /// To pass a single argument see [`arg`].
562 /// [`arg`]: Command::arg
569 /// use std::process::Command;
571 /// Command::new("ls")
572 /// .args(&["-l", "-a"])
574 /// .expect("ls command failed to start");
576 #[stable(feature = "process", since = "1.0.0")]
577 pub fn args<I, S>(&mut self, args: I) -> &mut Command
579 I: IntoIterator<Item = S>,
583 self.arg(arg.as_ref());
588 /// Inserts or updates an environment variable mapping.
590 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
591 /// and case-sensitive on all other platforms.
598 /// use std::process::Command;
600 /// Command::new("ls")
601 /// .env("PATH", "/bin")
603 /// .expect("ls command failed to start");
605 #[stable(feature = "process", since = "1.0.0")]
606 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
611 self.inner.env_mut().set(key.as_ref(), val.as_ref());
615 /// Adds or updates multiple environment variable mappings.
622 /// use std::process::{Command, Stdio};
624 /// use std::collections::HashMap;
626 /// let filtered_env : HashMap<String, String> =
627 /// env::vars().filter(|&(ref k, _)|
628 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
631 /// Command::new("printenv")
632 /// .stdin(Stdio::null())
633 /// .stdout(Stdio::inherit())
635 /// .envs(&filtered_env)
637 /// .expect("printenv failed to start");
639 #[stable(feature = "command_envs", since = "1.19.0")]
640 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
642 I: IntoIterator<Item = (K, V)>,
646 for (ref key, ref val) in vars {
647 self.inner.env_mut().set(key.as_ref(), val.as_ref());
652 /// Removes an environment variable mapping.
659 /// use std::process::Command;
661 /// Command::new("ls")
662 /// .env_remove("PATH")
664 /// .expect("ls command failed to start");
666 #[stable(feature = "process", since = "1.0.0")]
667 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
668 self.inner.env_mut().remove(key.as_ref());
672 /// Clears the entire environment map for the child process.
679 /// use std::process::Command;
681 /// Command::new("ls")
684 /// .expect("ls command failed to start");
686 #[stable(feature = "process", since = "1.0.0")]
687 pub fn env_clear(&mut self) -> &mut Command {
688 self.inner.env_mut().clear();
692 /// Sets the working directory for the child process.
694 /// # Platform-specific behavior
696 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
697 /// whether it should be interpreted relative to the parent's working
698 /// directory or relative to `current_dir`. The behavior in this case is
699 /// platform specific and unstable, and it's recommended to use
700 /// [`canonicalize`] to get an absolute program path instead.
707 /// use std::process::Command;
709 /// Command::new("ls")
710 /// .current_dir("/bin")
712 /// .expect("ls command failed to start");
715 /// [`canonicalize`]: crate::fs::canonicalize
716 #[stable(feature = "process", since = "1.0.0")]
717 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
718 self.inner.cwd(dir.as_ref().as_ref());
722 /// Configuration for the child process's standard input (stdin) handle.
724 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
725 /// defaults to [`piped`] when used with `output`.
727 /// [`inherit`]: Stdio::inherit
728 /// [`piped`]: Stdio::piped
735 /// use std::process::{Command, Stdio};
737 /// Command::new("ls")
738 /// .stdin(Stdio::null())
740 /// .expect("ls command failed to start");
742 #[stable(feature = "process", since = "1.0.0")]
743 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
744 self.inner.stdin(cfg.into().0);
748 /// Configuration for the child process's standard output (stdout) handle.
750 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
751 /// defaults to [`piped`] when used with `output`.
753 /// [`inherit`]: Stdio::inherit
754 /// [`piped`]: Stdio::piped
761 /// use std::process::{Command, Stdio};
763 /// Command::new("ls")
764 /// .stdout(Stdio::null())
766 /// .expect("ls command failed to start");
768 #[stable(feature = "process", since = "1.0.0")]
769 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
770 self.inner.stdout(cfg.into().0);
774 /// Configuration for the child process's standard error (stderr) handle.
776 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
777 /// defaults to [`piped`] when used with `output`.
779 /// [`inherit`]: Stdio::inherit
780 /// [`piped`]: Stdio::piped
787 /// use std::process::{Command, Stdio};
789 /// Command::new("ls")
790 /// .stderr(Stdio::null())
792 /// .expect("ls command failed to start");
794 #[stable(feature = "process", since = "1.0.0")]
795 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
796 self.inner.stderr(cfg.into().0);
800 /// Executes the command as a child process, returning a handle to it.
802 /// By default, stdin, stdout and stderr are inherited from the parent.
809 /// use std::process::Command;
811 /// Command::new("ls")
813 /// .expect("ls command failed to start");
815 #[stable(feature = "process", since = "1.0.0")]
816 pub fn spawn(&mut self) -> io::Result<Child> {
817 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
820 /// Executes the command as a child process, waiting for it to finish and
821 /// collecting all of its output.
823 /// By default, stdout and stderr are captured (and used to provide the
824 /// resulting output). Stdin is not inherited from the parent and any
825 /// attempt by the child process to read from the stdin stream will result
826 /// in the stream immediately closing.
831 /// use std::process::Command;
832 /// use std::io::{self, Write};
833 /// let output = Command::new("/bin/cat")
836 /// .expect("failed to execute process");
838 /// println!("status: {}", output.status);
839 /// io::stdout().write_all(&output.stdout).unwrap();
840 /// io::stderr().write_all(&output.stderr).unwrap();
842 /// assert!(output.status.success());
844 #[stable(feature = "process", since = "1.0.0")]
845 pub fn output(&mut self) -> io::Result<Output> {
847 .spawn(imp::Stdio::MakePipe, false)
848 .map(Child::from_inner)
849 .and_then(|p| p.wait_with_output())
852 /// Executes a command as a child process, waiting for it to finish and
853 /// collecting its exit status.
855 /// By default, stdin, stdout and stderr are inherited from the parent.
860 /// use std::process::Command;
862 /// let status = Command::new("/bin/cat")
865 /// .expect("failed to execute process");
867 /// println!("process exited with: {}", status);
869 /// assert!(status.success());
871 #[stable(feature = "process", since = "1.0.0")]
872 pub fn status(&mut self) -> io::Result<ExitStatus> {
874 .spawn(imp::Stdio::Inherit, true)
875 .map(Child::from_inner)
876 .and_then(|mut p| p.wait())
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl fmt::Debug for Command {
882 /// Format the program and arguments of a Command for display. Any
883 /// non-utf8 data is lossily converted using the utf8 replacement
885 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890 impl AsInner<imp::Command> for Command {
891 fn as_inner(&self) -> &imp::Command {
896 impl AsInnerMut<imp::Command> for Command {
897 fn as_inner_mut(&mut self) -> &mut imp::Command {
902 /// The output of a finished process.
904 /// This is returned in a Result by either the [`output`] method of a
905 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
908 /// [`output`]: Command::output
909 /// [`wait_with_output`]: Child::wait_with_output
910 #[derive(PartialEq, Eq, Clone)]
911 #[stable(feature = "process", since = "1.0.0")]
913 /// The status (exit code) of the process.
914 #[stable(feature = "process", since = "1.0.0")]
915 pub status: ExitStatus,
916 /// The data that the process wrote to stdout.
917 #[stable(feature = "process", since = "1.0.0")]
919 /// The data that the process wrote to stderr.
920 #[stable(feature = "process", since = "1.0.0")]
924 // If either stderr or stdout are valid utf8 strings it prints the valid
925 // strings, otherwise it prints the byte sequence instead
926 #[stable(feature = "process_output_debug", since = "1.7.0")]
927 impl fmt::Debug for Output {
928 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
929 let stdout_utf8 = str::from_utf8(&self.stdout);
930 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
932 Err(_) => &self.stdout,
935 let stderr_utf8 = str::from_utf8(&self.stderr);
936 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
938 Err(_) => &self.stderr,
941 fmt.debug_struct("Output")
942 .field("status", &self.status)
943 .field("stdout", stdout_debug)
944 .field("stderr", stderr_debug)
949 /// Describes what to do with a standard I/O stream for a child process when
950 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
952 /// [`stdin`]: Command::stdin
953 /// [`stdout`]: Command::stdout
954 /// [`stderr`]: Command::stderr
955 #[stable(feature = "process", since = "1.0.0")]
956 pub struct Stdio(imp::Stdio);
959 /// A new pipe should be arranged to connect the parent and child processes.
966 /// use std::process::{Command, Stdio};
968 /// let output = Command::new("echo")
969 /// .arg("Hello, world!")
970 /// .stdout(Stdio::piped())
972 /// .expect("Failed to execute command");
974 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
975 /// // Nothing echoed to console
981 /// use std::io::Write;
982 /// use std::process::{Command, Stdio};
984 /// let mut child = Command::new("rev")
985 /// .stdin(Stdio::piped())
986 /// .stdout(Stdio::piped())
988 /// .expect("Failed to spawn child process");
991 /// let stdin = child.stdin.as_mut().expect("Failed to open stdin");
992 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
995 /// let output = child.wait_with_output().expect("Failed to read stdout");
996 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
998 #[stable(feature = "process", since = "1.0.0")]
999 pub fn piped() -> Stdio {
1000 Stdio(imp::Stdio::MakePipe)
1003 /// The child inherits from the corresponding parent descriptor.
1010 /// use std::process::{Command, Stdio};
1012 /// let output = Command::new("echo")
1013 /// .arg("Hello, world!")
1014 /// .stdout(Stdio::inherit())
1016 /// .expect("Failed to execute command");
1018 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1019 /// // "Hello, world!" echoed to console
1025 /// use std::process::{Command, Stdio};
1026 /// use std::io::{self, Write};
1028 /// let output = Command::new("rev")
1029 /// .stdin(Stdio::inherit())
1030 /// .stdout(Stdio::piped())
1032 /// .expect("Failed to execute command");
1034 /// print!("You piped in the reverse of: ");
1035 /// io::stdout().write_all(&output.stdout).unwrap();
1037 #[stable(feature = "process", since = "1.0.0")]
1038 pub fn inherit() -> Stdio {
1039 Stdio(imp::Stdio::Inherit)
1042 /// This stream will be ignored. This is the equivalent of attaching the
1043 /// stream to `/dev/null`
1050 /// use std::process::{Command, Stdio};
1052 /// let output = Command::new("echo")
1053 /// .arg("Hello, world!")
1054 /// .stdout(Stdio::null())
1056 /// .expect("Failed to execute command");
1058 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1059 /// // Nothing echoed to console
1065 /// use std::process::{Command, Stdio};
1067 /// let output = Command::new("rev")
1068 /// .stdin(Stdio::null())
1069 /// .stdout(Stdio::piped())
1071 /// .expect("Failed to execute command");
1073 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1074 /// // Ignores any piped-in input
1076 #[stable(feature = "process", since = "1.0.0")]
1077 pub fn null() -> Stdio {
1078 Stdio(imp::Stdio::Null)
1082 impl FromInner<imp::Stdio> for Stdio {
1083 fn from_inner(inner: imp::Stdio) -> Stdio {
1088 #[stable(feature = "std_debug", since = "1.16.0")]
1089 impl fmt::Debug for Stdio {
1090 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1091 f.pad("Stdio { .. }")
1095 #[stable(feature = "stdio_from", since = "1.20.0")]
1096 impl From<ChildStdin> for Stdio {
1097 /// Converts a `ChildStdin` into a `Stdio`
1101 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1104 /// use std::process::{Command, Stdio};
1106 /// let reverse = Command::new("rev")
1107 /// .stdin(Stdio::piped())
1109 /// .expect("failed reverse command");
1111 /// let _echo = Command::new("echo")
1112 /// .arg("Hello, world!")
1113 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1115 /// .expect("failed echo command");
1117 /// // "!dlrow ,olleH" echoed to console
1119 fn from(child: ChildStdin) -> Stdio {
1120 Stdio::from_inner(child.into_inner().into())
1124 #[stable(feature = "stdio_from", since = "1.20.0")]
1125 impl From<ChildStdout> for Stdio {
1126 /// Converts a `ChildStdout` into a `Stdio`
1130 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1133 /// use std::process::{Command, Stdio};
1135 /// let hello = Command::new("echo")
1136 /// .arg("Hello, world!")
1137 /// .stdout(Stdio::piped())
1139 /// .expect("failed echo command");
1141 /// let reverse = Command::new("rev")
1142 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1144 /// .expect("failed reverse command");
1146 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1148 fn from(child: ChildStdout) -> Stdio {
1149 Stdio::from_inner(child.into_inner().into())
1153 #[stable(feature = "stdio_from", since = "1.20.0")]
1154 impl From<ChildStderr> for Stdio {
1155 /// Converts a `ChildStderr` into a `Stdio`
1160 /// use std::process::{Command, Stdio};
1162 /// let reverse = Command::new("rev")
1163 /// .arg("non_existing_file.txt")
1164 /// .stderr(Stdio::piped())
1166 /// .expect("failed reverse command");
1168 /// let cat = Command::new("cat")
1170 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1172 /// .expect("failed echo command");
1175 /// String::from_utf8_lossy(&cat.stdout),
1176 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1179 fn from(child: ChildStderr) -> Stdio {
1180 Stdio::from_inner(child.into_inner().into())
1184 #[stable(feature = "stdio_from", since = "1.20.0")]
1185 impl From<fs::File> for Stdio {
1186 /// Converts a `File` into a `Stdio`
1190 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1193 /// use std::fs::File;
1194 /// use std::process::Command;
1196 /// // With the `foo.txt` file containing `Hello, world!"
1197 /// let file = File::open("foo.txt").unwrap();
1199 /// let reverse = Command::new("rev")
1200 /// .stdin(file) // Implicit File conversion into a Stdio
1202 /// .expect("failed reverse command");
1204 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1206 fn from(file: fs::File) -> Stdio {
1207 Stdio::from_inner(file.into_inner().into())
1211 /// Describes the result of a process after it has terminated.
1213 /// This `struct` is used to represent the exit status of a child process.
1214 /// Child processes are created via the [`Command`] struct and their exit
1215 /// status is exposed through the [`status`] method, or the [`wait`] method
1216 /// of a [`Child`] process.
1218 /// [`status`]: Command::status
1219 /// [`wait`]: Child::wait
1220 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1221 #[stable(feature = "process", since = "1.0.0")]
1222 pub struct ExitStatus(imp::ExitStatus);
1225 /// Was termination successful? Signal termination is not considered a
1226 /// success, and success is defined as a zero exit status.
1231 /// use std::process::Command;
1233 /// let status = Command::new("mkdir")
1234 /// .arg("projects")
1236 /// .expect("failed to execute mkdir");
1238 /// if status.success() {
1239 /// println!("'projects/' directory created");
1241 /// println!("failed to create 'projects/' directory");
1244 #[stable(feature = "process", since = "1.0.0")]
1245 pub fn success(&self) -> bool {
1249 /// Returns the exit code of the process, if any.
1251 /// On Unix, this will return `None` if the process was terminated
1252 /// by a signal; `std::os::unix` provides an extension trait for
1253 /// extracting the signal and other details from the `ExitStatus`.
1258 /// use std::process::Command;
1260 /// let status = Command::new("mkdir")
1261 /// .arg("projects")
1263 /// .expect("failed to execute mkdir");
1265 /// match status.code() {
1266 /// Some(code) => println!("Exited with status code: {}", code),
1267 /// None => println!("Process terminated by signal")
1270 #[stable(feature = "process", since = "1.0.0")]
1271 pub fn code(&self) -> Option<i32> {
1276 impl AsInner<imp::ExitStatus> for ExitStatus {
1277 fn as_inner(&self) -> &imp::ExitStatus {
1282 impl FromInner<imp::ExitStatus> for ExitStatus {
1283 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1288 #[stable(feature = "process", since = "1.0.0")]
1289 impl fmt::Display for ExitStatus {
1290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1295 /// This type represents the status code a process can return to its
1296 /// parent under normal termination.
1298 /// Numeric values used in this type don't have portable meanings, and
1299 /// different platforms may mask different amounts of them.
1301 /// For the platform's canonical successful and unsuccessful codes, see
1302 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1304 /// [`SUCCESS`]: ExitCode::SUCCESS
1305 /// [`FAILURE`]: ExitCode::FAILURE
1307 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1308 /// it was ultimately cut from that RFC, and thus this type is more subject
1309 /// to change even than the usual unstable item churn.
1311 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1312 #[derive(Clone, Copy, Debug)]
1313 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1314 pub struct ExitCode(imp::ExitCode);
1316 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1318 /// The canonical ExitCode for successful termination on this platform.
1320 /// Note that a `()`-returning `main` implicitly results in a successful
1321 /// termination, so there's no need to return this from `main` unless
1322 /// you're also returning other possible codes.
1323 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1324 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1326 /// The canonical ExitCode for unsuccessful termination on this platform.
1328 /// If you're only returning this and `SUCCESS` from `main`, consider
1329 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1330 /// return the same codes (but will also `eprintln!` the error).
1331 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1332 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1336 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1337 /// error is returned.
1339 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1340 /// especially the [`Other`] kind might change to more specific kinds in the future.
1342 /// This is equivalent to sending a SIGKILL on Unix platforms.
1349 /// use std::process::Command;
1351 /// let mut command = Command::new("yes");
1352 /// if let Ok(mut child) = command.spawn() {
1353 /// child.kill().expect("command wasn't running");
1355 /// println!("yes command didn't start");
1359 /// [`ErrorKind`]: io::ErrorKind
1360 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1361 /// [`Other`]: io::ErrorKind::Other
1362 #[stable(feature = "process", since = "1.0.0")]
1363 pub fn kill(&mut self) -> io::Result<()> {
1367 /// Returns the OS-assigned process identifier associated with this child.
1374 /// use std::process::Command;
1376 /// let mut command = Command::new("ls");
1377 /// if let Ok(child) = command.spawn() {
1378 /// println!("Child's ID is {}", child.id());
1380 /// println!("ls command didn't start");
1383 #[stable(feature = "process_id", since = "1.3.0")]
1384 pub fn id(&self) -> u32 {
1388 /// Waits for the child to exit completely, returning the status that it
1389 /// exited with. This function will continue to have the same return value
1390 /// after it has been called at least once.
1392 /// The stdin handle to the child process, if any, will be closed
1393 /// before waiting. This helps avoid deadlock: it ensures that the
1394 /// child does not block waiting for input from the parent, while
1395 /// the parent waits for the child to exit.
1402 /// use std::process::Command;
1404 /// let mut command = Command::new("ls");
1405 /// if let Ok(mut child) = command.spawn() {
1406 /// child.wait().expect("command wasn't running");
1407 /// println!("Child has finished its execution!");
1409 /// println!("ls command didn't start");
1412 #[stable(feature = "process", since = "1.0.0")]
1413 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1414 drop(self.stdin.take());
1415 self.handle.wait().map(ExitStatus)
1418 /// Attempts to collect the exit status of the child if it has already
1421 /// This function will not block the calling thread and will only
1422 /// check to see if the child process has exited or not. If the child has
1423 /// exited then on Unix the process ID is reaped. This function is
1424 /// guaranteed to repeatedly return a successful exit status so long as the
1425 /// child has already exited.
1427 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1428 /// exit status is not available at this time then `Ok(None)` is returned.
1429 /// If an error occurs, then that error is returned.
1431 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1438 /// use std::process::Command;
1440 /// let mut child = Command::new("ls").spawn().unwrap();
1442 /// match child.try_wait() {
1443 /// Ok(Some(status)) => println!("exited with: {}", status),
1445 /// println!("status not ready yet, let's really wait");
1446 /// let res = child.wait();
1447 /// println!("result: {:?}", res);
1449 /// Err(e) => println!("error attempting to wait: {}", e),
1452 #[stable(feature = "process_try_wait", since = "1.18.0")]
1453 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1454 Ok(self.handle.try_wait()?.map(ExitStatus))
1457 /// Simultaneously waits for the child to exit and collect all remaining
1458 /// output on the stdout/stderr handles, returning an `Output`
1461 /// The stdin handle to the child process, if any, will be closed
1462 /// before waiting. This helps avoid deadlock: it ensures that the
1463 /// child does not block waiting for input from the parent, while
1464 /// the parent waits for the child to exit.
1466 /// By default, stdin, stdout and stderr are inherited from the parent.
1467 /// In order to capture the output into this `Result<Output>` it is
1468 /// necessary to create new pipes between parent and child. Use
1469 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1474 /// use std::process::{Command, Stdio};
1476 /// let child = Command::new("/bin/cat")
1477 /// .arg("file.txt")
1478 /// .stdout(Stdio::piped())
1480 /// .expect("failed to execute child");
1482 /// let output = child
1483 /// .wait_with_output()
1484 /// .expect("failed to wait on child");
1486 /// assert!(output.status.success());
1489 #[stable(feature = "process", since = "1.0.0")]
1490 pub fn wait_with_output(mut self) -> io::Result<Output> {
1491 drop(self.stdin.take());
1493 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1494 match (self.stdout.take(), self.stderr.take()) {
1496 (Some(mut out), None) => {
1497 let res = out.read_to_end(&mut stdout);
1500 (None, Some(mut err)) => {
1501 let res = err.read_to_end(&mut stderr);
1504 (Some(out), Some(err)) => {
1505 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1510 let status = self.wait()?;
1511 Ok(Output { status, stdout, stderr })
1515 /// Terminates the current process with the specified exit code.
1517 /// This function will never return and will immediately terminate the current
1518 /// process. The exit code is passed through to the underlying OS and will be
1519 /// available for consumption by another process.
1521 /// Note that because this function never returns, and that it terminates the
1522 /// process, no destructors on the current stack or any other thread's stack
1523 /// will be run. If a clean shutdown is needed it is recommended to only call
1524 /// this function at a known point where there are no more destructors left
1527 /// ## Platform-specific behavior
1529 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1530 /// will be visible to a parent process inspecting the exit code. On most
1531 /// Unix-like platforms, only the eight least-significant bits are considered.
1535 /// Due to this function’s behavior regarding destructors, a conventional way
1536 /// to use the function is to extract the actual computation to another
1537 /// function and compute the exit code from its return value:
1540 /// fn run_app() -> Result<(), ()> {
1541 /// // Application logic here
1546 /// std::process::exit(match run_app() {
1549 /// eprintln!("error: {:?}", err);
1556 /// Due to [platform-specific behavior], the exit code for this example will be
1557 /// `0` on Linux, but `256` on Windows:
1560 /// use std::process;
1562 /// process::exit(0x0100);
1565 /// [platform-specific behavior]: #platform-specific-behavior
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 pub fn exit(code: i32) -> ! {
1568 crate::sys_common::cleanup();
1569 crate::sys::os::exit(code)
1572 /// Terminates the process in an abnormal fashion.
1574 /// The function will never return and will immediately terminate the current
1575 /// process in a platform specific "abnormal" manner.
1577 /// Note that because this function never returns, and that it terminates the
1578 /// process, no destructors on the current stack or any other thread's stack
1581 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1582 /// the current thread's stack and calls all destructors.
1583 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1584 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1585 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1587 /// If a clean shutdown is needed it is recommended to only call
1588 /// this function at a known point where there are no more destructors left
1594 /// use std::process;
1597 /// println!("aborting");
1599 /// process::abort();
1601 /// // execution never gets here
1605 /// The `abort` function terminates the process, so the destructor will not
1606 /// get run on the example below:
1609 /// use std::process;
1613 /// impl Drop for HasDrop {
1614 /// fn drop(&mut self) {
1615 /// println!("This will never be printed!");
1620 /// let _x = HasDrop;
1621 /// process::abort();
1622 /// // the destructor implemented for HasDrop will never get run
1626 /// [panic hook]: crate::panic::set_hook
1627 #[stable(feature = "process_abort", since = "1.17.0")]
1628 pub fn abort() -> ! {
1629 crate::sys::abort_internal();
1632 /// Returns the OS-assigned process identifier associated with this process.
1639 /// use std::process;
1641 /// println!("My pid is {}", process::id());
1645 #[stable(feature = "getpid", since = "1.26.0")]
1646 pub fn id() -> u32 {
1647 crate::sys::os::getpid()
1650 /// A trait for implementing arbitrary return types in the `main` function.
1652 /// The C-main function only supports to return integers as return type.
1653 /// So, every type implementing the `Termination` trait has to be converted
1656 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1657 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1658 #[cfg_attr(not(test), lang = "termination")]
1659 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1660 #[rustc_on_unimplemented(
1661 message = "`main` has invalid return type `{Self}`",
1662 label = "`main` can only return types that implement `{Termination}`"
1664 pub trait Termination {
1665 /// Is called to get the representation of the value as status code.
1666 /// This status code is returned to the operating system.
1667 fn report(self) -> i32;
1670 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1671 impl Termination for () {
1673 fn report(self) -> i32 {
1674 ExitCode::SUCCESS.report()
1678 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1679 impl<E: fmt::Debug> Termination for Result<(), E> {
1680 fn report(self) -> i32 {
1682 Ok(()) => ().report(),
1683 Err(err) => Err::<!, _>(err).report(),
1688 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1689 impl Termination for ! {
1690 fn report(self) -> i32 {
1695 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1696 impl<E: fmt::Debug> Termination for Result<!, E> {
1697 fn report(self) -> i32 {
1698 let Err(err) = self;
1699 eprintln!("Error: {:?}", err);
1700 ExitCode::FAILURE.report()
1704 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1705 impl Termination for ExitCode {
1707 fn report(self) -> i32 {