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");
74 //! // If the child process fills its stdout buffer, it may end up
75 //! // waiting until the parent reads the stdout, and not be able to
76 //! // read stdin in the meantime, causing a deadlock.
77 //! // Writing from another thread ensures that stdout is being read
78 //! // at the same time, avoiding the problem.
79 //! let mut stdin = child.stdin.take().expect("failed to get stdin");
80 //! std::thread::spawn(move || {
81 //! stdin.write_all(b"test").expect("failed to write to stdin");
84 //! let output = child
85 //! .wait_with_output()
86 //! .expect("failed to wait on child");
88 //! assert_eq!(b"test", output.stdout.as_slice());
91 //! [`spawn`]: Command::spawn
92 //! [`output`]: Command::output
94 //! [`stdout`]: Command::stdout
95 //! [`stdin`]: Command::stdin
96 //! [`stderr`]: Command::stderr
98 //! [`Write`]: io::Write
99 //! [`Read`]: io::Read
101 #![stable(feature = "process", since = "1.0.0")]
102 #![deny(unsafe_op_in_unsafe_fn)]
104 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
107 use crate::io::prelude::*;
109 use crate::ffi::OsStr;
112 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
113 use crate::num::NonZeroI32;
114 use crate::path::Path;
116 use crate::sys::pipe::{read2, AnonPipe};
117 use crate::sys::process as imp;
118 #[unstable(feature = "command_access", issue = "44434")]
119 pub use crate::sys_common::process::CommandEnvs;
120 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
122 /// Representation of a running or exited child process.
124 /// This structure is used to represent and manage child processes. A child
125 /// process is created via the [`Command`] struct, which configures the
126 /// spawning process and can itself be constructed using a builder-style
129 /// There is no implementation of [`Drop`] for child processes,
130 /// so if you do not ensure the `Child` has exited then it will continue to
131 /// run, even after the `Child` handle to the child process has gone out of
134 /// Calling [`wait`] (or other functions that wrap around it) will make
135 /// the parent process wait until the child has actually exited before
140 /// On some systems, calling [`wait`] or similar is necessary for the OS to
141 /// release resources. A process that terminated but has not been waited on is
142 /// still around as a "zombie". Leaving too many zombies around may exhaust
143 /// global resources (for example process IDs).
145 /// The standard library does *not* automatically wait on child processes (not
146 /// even if the `Child` is dropped), it is up to the application developer to do
147 /// so. As a consequence, dropping `Child` handles without waiting on them first
148 /// is not recommended in long-running applications.
153 /// use std::process::Command;
155 /// let mut child = Command::new("/bin/cat")
158 /// .expect("failed to execute child");
160 /// let ecode = child.wait()
161 /// .expect("failed to wait on child");
163 /// assert!(ecode.success());
166 /// [`wait`]: Child::wait
167 #[stable(feature = "process", since = "1.0.0")]
169 pub(crate) handle: imp::Process,
171 /// The handle for writing to the child's standard input (stdin), if it has
172 /// been captured. To avoid partially moving
173 /// the `child` and thus blocking yourself from calling
174 /// functions on `child` while using `stdin`,
175 /// you might find it helpful:
177 /// ```compile_fail,E0425
178 /// let stdin = child.stdin.take().unwrap();
180 #[stable(feature = "process", since = "1.0.0")]
181 pub stdin: Option<ChildStdin>,
183 /// The handle for reading from the child's standard output (stdout), if it
184 /// has been captured. You might find it helpful to do
186 /// ```compile_fail,E0425
187 /// let stdout = child.stdout.take().unwrap();
190 /// to avoid partially moving the `child` and thus blocking yourself from calling
191 /// functions on `child` while using `stdout`.
192 #[stable(feature = "process", since = "1.0.0")]
193 pub stdout: Option<ChildStdout>,
195 /// The handle for reading from the child's standard error (stderr), if it
196 /// has been captured. You might find it helpful to do
198 /// ```compile_fail,E0425
199 /// let stderr = child.stderr.take().unwrap();
202 /// to avoid partially moving the `child` and thus blocking yourself from calling
203 /// functions on `child` while using `stderr`.
204 #[stable(feature = "process", since = "1.0.0")]
205 pub stderr: Option<ChildStderr>,
208 /// Allows extension traits within `std`.
209 #[unstable(feature = "sealed", issue = "none")]
210 impl crate::sealed::Sealed for Child {}
212 impl AsInner<imp::Process> for Child {
213 fn as_inner(&self) -> &imp::Process {
218 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
219 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
222 stdin: io.stdin.map(ChildStdin::from_inner),
223 stdout: io.stdout.map(ChildStdout::from_inner),
224 stderr: io.stderr.map(ChildStderr::from_inner),
229 impl IntoInner<imp::Process> for Child {
230 fn into_inner(self) -> imp::Process {
235 #[stable(feature = "std_debug", since = "1.16.0")]
236 impl fmt::Debug for Child {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.debug_struct("Child")
239 .field("stdin", &self.stdin)
240 .field("stdout", &self.stdout)
241 .field("stderr", &self.stderr)
242 .finish_non_exhaustive()
246 /// A handle to a child process's standard input (stdin).
248 /// This struct is used in the [`stdin`] field on [`Child`].
250 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
251 /// file handle will be closed. If the child process was blocked on input prior
252 /// to being dropped, it will become unblocked after dropping.
254 /// [`stdin`]: Child::stdin
256 #[stable(feature = "process", since = "1.0.0")]
257 pub struct ChildStdin {
261 #[stable(feature = "process", since = "1.0.0")]
262 impl Write for ChildStdin {
263 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
267 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
268 (&*self).write_vectored(bufs)
271 fn is_write_vectored(&self) -> bool {
272 io::Write::is_write_vectored(&&*self)
275 fn flush(&mut self) -> io::Result<()> {
280 #[stable(feature = "write_mt", since = "1.48.0")]
281 impl Write for &ChildStdin {
282 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
283 self.inner.write(buf)
286 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
287 self.inner.write_vectored(bufs)
290 fn is_write_vectored(&self) -> bool {
291 self.inner.is_write_vectored()
294 fn flush(&mut self) -> io::Result<()> {
299 impl AsInner<AnonPipe> for ChildStdin {
300 fn as_inner(&self) -> &AnonPipe {
305 impl IntoInner<AnonPipe> for ChildStdin {
306 fn into_inner(self) -> AnonPipe {
311 impl FromInner<AnonPipe> for ChildStdin {
312 fn from_inner(pipe: AnonPipe) -> ChildStdin {
313 ChildStdin { inner: pipe }
317 #[stable(feature = "std_debug", since = "1.16.0")]
318 impl fmt::Debug for ChildStdin {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 f.debug_struct("ChildStdin").finish_non_exhaustive()
324 /// A handle to a child process's standard output (stdout).
326 /// This struct is used in the [`stdout`] field on [`Child`].
328 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
329 /// underlying file handle will be closed.
331 /// [`stdout`]: Child::stdout
333 #[stable(feature = "process", since = "1.0.0")]
334 pub struct ChildStdout {
338 #[stable(feature = "process", since = "1.0.0")]
339 impl Read for ChildStdout {
340 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
344 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
345 self.inner.read_vectored(bufs)
349 fn is_read_vectored(&self) -> bool {
350 self.inner.is_read_vectored()
354 unsafe fn initializer(&self) -> Initializer {
355 // SAFETY: Read is guaranteed to work on uninitialized memory
356 unsafe { Initializer::nop() }
360 impl AsInner<AnonPipe> for ChildStdout {
361 fn as_inner(&self) -> &AnonPipe {
366 impl IntoInner<AnonPipe> for ChildStdout {
367 fn into_inner(self) -> AnonPipe {
372 impl FromInner<AnonPipe> for ChildStdout {
373 fn from_inner(pipe: AnonPipe) -> ChildStdout {
374 ChildStdout { inner: pipe }
378 #[stable(feature = "std_debug", since = "1.16.0")]
379 impl fmt::Debug for ChildStdout {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 f.debug_struct("ChildStdout").finish_non_exhaustive()
385 /// A handle to a child process's stderr.
387 /// This struct is used in the [`stderr`] field on [`Child`].
389 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
390 /// underlying file handle will be closed.
392 /// [`stderr`]: Child::stderr
394 #[stable(feature = "process", since = "1.0.0")]
395 pub struct ChildStderr {
399 #[stable(feature = "process", since = "1.0.0")]
400 impl Read for ChildStderr {
401 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
405 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
406 self.inner.read_vectored(bufs)
410 fn is_read_vectored(&self) -> bool {
411 self.inner.is_read_vectored()
415 unsafe fn initializer(&self) -> Initializer {
416 // SAFETY: Read is guaranteed to work on uninitialized memory
417 unsafe { Initializer::nop() }
421 impl AsInner<AnonPipe> for ChildStderr {
422 fn as_inner(&self) -> &AnonPipe {
427 impl IntoInner<AnonPipe> for ChildStderr {
428 fn into_inner(self) -> AnonPipe {
433 impl FromInner<AnonPipe> for ChildStderr {
434 fn from_inner(pipe: AnonPipe) -> ChildStderr {
435 ChildStderr { inner: pipe }
439 #[stable(feature = "std_debug", since = "1.16.0")]
440 impl fmt::Debug for ChildStderr {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 f.debug_struct("ChildStderr").finish_non_exhaustive()
446 /// A process builder, providing fine-grained control
447 /// over how a new process should be spawned.
449 /// A default configuration can be
450 /// generated using `Command::new(program)`, where `program` gives a path to the
451 /// program to be executed. Additional builder methods allow the configuration
452 /// to be changed (for example, by adding arguments) prior to spawning:
455 /// use std::process::Command;
457 /// let output = if cfg!(target_os = "windows") {
458 /// Command::new("cmd")
459 /// .args(["/C", "echo hello"])
461 /// .expect("failed to execute process")
463 /// Command::new("sh")
465 /// .arg("echo hello")
467 /// .expect("failed to execute process")
470 /// let hello = output.stdout;
473 /// `Command` can be reused to spawn multiple processes. The builder methods
474 /// change the command without needing to immediately spawn the process.
477 /// use std::process::Command;
479 /// let mut echo_hello = Command::new("sh");
480 /// echo_hello.arg("-c")
481 /// .arg("echo hello");
482 /// let hello_1 = echo_hello.output().expect("failed to execute process");
483 /// let hello_2 = echo_hello.output().expect("failed to execute process");
486 /// Similarly, you can call builder methods after spawning a process and then
487 /// spawn a new process with the modified settings.
490 /// use std::process::Command;
492 /// let mut list_dir = Command::new("ls");
494 /// // Execute `ls` in the current directory of the program.
495 /// list_dir.status().expect("process failed to execute");
499 /// // Change `ls` to execute in the root directory.
500 /// list_dir.current_dir("/");
502 /// // And then execute `ls` again but in the root directory.
503 /// list_dir.status().expect("process failed to execute");
505 #[stable(feature = "process", since = "1.0.0")]
510 /// Allows extension traits within `std`.
511 #[unstable(feature = "sealed", issue = "none")]
512 impl crate::sealed::Sealed for Command {}
515 /// Constructs a new `Command` for launching the program at
516 /// path `program`, with the following default configuration:
518 /// * No arguments to the program
519 /// * Inherit the current process's environment
520 /// * Inherit the current process's working directory
521 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
523 /// Builder methods are provided to change these defaults and
524 /// otherwise configure the process.
526 /// If `program` is not an absolute path, the `PATH` will be searched in
527 /// an OS-defined way.
529 /// The search path to be used may be controlled by setting the
530 /// `PATH` environment variable on the Command,
531 /// but this has some implementation limitations on Windows
532 /// (see issue #37519).
539 /// use std::process::Command;
541 /// Command::new("sh")
543 /// .expect("sh command failed to start");
545 #[stable(feature = "process", since = "1.0.0")]
546 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
547 Command { inner: imp::Command::new(program.as_ref()) }
550 /// Adds an argument to pass to the program.
552 /// Only one argument can be passed per use. So instead of:
555 /// # std::process::Command::new("sh")
556 /// .arg("-C /path/to/repo")
563 /// # std::process::Command::new("sh")
565 /// .arg("/path/to/repo")
569 /// To pass multiple arguments see [`args`].
571 /// [`args`]: Command::args
573 /// Note that the argument is not passed through a shell, but given
574 /// literally to the program. This means that shell syntax like quotes,
575 /// escaped characters, word splitting, glob patterns, substitution, etc.
583 /// use std::process::Command;
585 /// Command::new("ls")
589 /// .expect("ls command failed to start");
591 #[stable(feature = "process", since = "1.0.0")]
592 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
593 self.inner.arg(arg.as_ref());
597 /// Adds multiple arguments to pass to the program.
599 /// To pass a single argument see [`arg`].
601 /// [`arg`]: Command::arg
603 /// Note that the arguments are not passed through a shell, but given
604 /// literally to the program. This means that shell syntax like quotes,
605 /// escaped characters, word splitting, glob patterns, substitution, etc.
613 /// use std::process::Command;
615 /// Command::new("ls")
616 /// .args(["-l", "-a"])
618 /// .expect("ls command failed to start");
620 #[stable(feature = "process", since = "1.0.0")]
621 pub fn args<I, S>(&mut self, args: I) -> &mut Command
623 I: IntoIterator<Item = S>,
627 self.arg(arg.as_ref());
632 /// Inserts or updates an environment variable mapping.
634 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
635 /// and case-sensitive on all other platforms.
642 /// use std::process::Command;
644 /// Command::new("ls")
645 /// .env("PATH", "/bin")
647 /// .expect("ls command failed to start");
649 #[stable(feature = "process", since = "1.0.0")]
650 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
655 self.inner.env_mut().set(key.as_ref(), val.as_ref());
659 /// Adds or updates multiple environment variable mappings.
666 /// use std::process::{Command, Stdio};
668 /// use std::collections::HashMap;
670 /// let filtered_env : HashMap<String, String> =
671 /// env::vars().filter(|&(ref k, _)|
672 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
675 /// Command::new("printenv")
676 /// .stdin(Stdio::null())
677 /// .stdout(Stdio::inherit())
679 /// .envs(&filtered_env)
681 /// .expect("printenv failed to start");
683 #[stable(feature = "command_envs", since = "1.19.0")]
684 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
686 I: IntoIterator<Item = (K, V)>,
690 for (ref key, ref val) in vars {
691 self.inner.env_mut().set(key.as_ref(), val.as_ref());
696 /// Removes an environment variable mapping.
703 /// use std::process::Command;
705 /// Command::new("ls")
706 /// .env_remove("PATH")
708 /// .expect("ls command failed to start");
710 #[stable(feature = "process", since = "1.0.0")]
711 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
712 self.inner.env_mut().remove(key.as_ref());
716 /// Clears the entire environment map for the child process.
723 /// use std::process::Command;
725 /// Command::new("ls")
728 /// .expect("ls command failed to start");
730 #[stable(feature = "process", since = "1.0.0")]
731 pub fn env_clear(&mut self) -> &mut Command {
732 self.inner.env_mut().clear();
736 /// Sets the working directory for the child process.
738 /// # Platform-specific behavior
740 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
741 /// whether it should be interpreted relative to the parent's working
742 /// directory or relative to `current_dir`. The behavior in this case is
743 /// platform specific and unstable, and it's recommended to use
744 /// [`canonicalize`] to get an absolute program path instead.
751 /// use std::process::Command;
753 /// Command::new("ls")
754 /// .current_dir("/bin")
756 /// .expect("ls command failed to start");
759 /// [`canonicalize`]: crate::fs::canonicalize
760 #[stable(feature = "process", since = "1.0.0")]
761 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
762 self.inner.cwd(dir.as_ref().as_ref());
766 /// Configuration for the child process's standard input (stdin) handle.
768 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
769 /// defaults to [`piped`] when used with `output`.
771 /// [`inherit`]: Stdio::inherit
772 /// [`piped`]: Stdio::piped
779 /// use std::process::{Command, Stdio};
781 /// Command::new("ls")
782 /// .stdin(Stdio::null())
784 /// .expect("ls command failed to start");
786 #[stable(feature = "process", since = "1.0.0")]
787 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
788 self.inner.stdin(cfg.into().0);
792 /// Configuration for the child process's standard output (stdout) handle.
794 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
795 /// defaults to [`piped`] when used with `output`.
797 /// [`inherit`]: Stdio::inherit
798 /// [`piped`]: Stdio::piped
805 /// use std::process::{Command, Stdio};
807 /// Command::new("ls")
808 /// .stdout(Stdio::null())
810 /// .expect("ls command failed to start");
812 #[stable(feature = "process", since = "1.0.0")]
813 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
814 self.inner.stdout(cfg.into().0);
818 /// Configuration for the child process's standard error (stderr) handle.
820 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
821 /// defaults to [`piped`] when used with `output`.
823 /// [`inherit`]: Stdio::inherit
824 /// [`piped`]: Stdio::piped
831 /// use std::process::{Command, Stdio};
833 /// Command::new("ls")
834 /// .stderr(Stdio::null())
836 /// .expect("ls command failed to start");
838 #[stable(feature = "process", since = "1.0.0")]
839 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
840 self.inner.stderr(cfg.into().0);
844 /// Executes the command as a child process, returning a handle to it.
846 /// By default, stdin, stdout and stderr are inherited from the parent.
853 /// use std::process::Command;
855 /// Command::new("ls")
857 /// .expect("ls command failed to start");
859 #[stable(feature = "process", since = "1.0.0")]
860 pub fn spawn(&mut self) -> io::Result<Child> {
861 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
864 /// Executes the command as a child process, waiting for it to finish and
865 /// collecting all of its output.
867 /// By default, stdout and stderr are captured (and used to provide the
868 /// resulting output). Stdin is not inherited from the parent and any
869 /// attempt by the child process to read from the stdin stream will result
870 /// in the stream immediately closing.
875 /// use std::process::Command;
876 /// use std::io::{self, Write};
877 /// let output = Command::new("/bin/cat")
880 /// .expect("failed to execute process");
882 /// println!("status: {}", output.status);
883 /// io::stdout().write_all(&output.stdout).unwrap();
884 /// io::stderr().write_all(&output.stderr).unwrap();
886 /// assert!(output.status.success());
888 #[stable(feature = "process", since = "1.0.0")]
889 pub fn output(&mut self) -> io::Result<Output> {
891 .spawn(imp::Stdio::MakePipe, false)
892 .map(Child::from_inner)
893 .and_then(|p| p.wait_with_output())
896 /// Executes a command as a child process, waiting for it to finish and
897 /// collecting its status.
899 /// By default, stdin, stdout and stderr are inherited from the parent.
904 /// use std::process::Command;
906 /// let status = Command::new("/bin/cat")
909 /// .expect("failed to execute process");
911 /// println!("process finished with: {}", status);
913 /// assert!(status.success());
915 #[stable(feature = "process", since = "1.0.0")]
916 pub fn status(&mut self) -> io::Result<ExitStatus> {
918 .spawn(imp::Stdio::Inherit, true)
919 .map(Child::from_inner)
920 .and_then(|mut p| p.wait())
923 /// Returns the path to the program that was given to [`Command::new`].
928 /// # #![feature(command_access)]
929 /// use std::process::Command;
931 /// let cmd = Command::new("echo");
932 /// assert_eq!(cmd.get_program(), "echo");
934 #[unstable(feature = "command_access", issue = "44434")]
935 pub fn get_program(&self) -> &OsStr {
936 self.inner.get_program()
939 /// Returns an iterator of the arguments that will be passed to the program.
941 /// This does not include the path to the program as the first argument;
942 /// it only includes the arguments specified with [`Command::arg`] and
943 /// [`Command::args`].
948 /// # #![feature(command_access)]
949 /// use std::ffi::OsStr;
950 /// use std::process::Command;
952 /// let mut cmd = Command::new("echo");
953 /// cmd.arg("first").arg("second");
954 /// let args: Vec<&OsStr> = cmd.get_args().collect();
955 /// assert_eq!(args, &["first", "second"]);
957 #[unstable(feature = "command_access", issue = "44434")]
958 pub fn get_args(&self) -> CommandArgs<'_> {
959 CommandArgs { inner: self.inner.get_args() }
962 /// Returns an iterator of the environment variables that will be set when
963 /// the process is spawned.
965 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
966 /// value is the key, and the second is the value, which is [`None`] if
967 /// the environment variable is to be explicitly removed.
969 /// This only includes environment variables explicitly set with
970 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
971 /// does not include environment variables that will be inherited by the
977 /// # #![feature(command_access)]
978 /// use std::ffi::OsStr;
979 /// use std::process::Command;
981 /// let mut cmd = Command::new("ls");
982 /// cmd.env("TERM", "dumb").env_remove("TZ");
983 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
984 /// assert_eq!(envs, &[
985 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
986 /// (OsStr::new("TZ"), None)
989 #[unstable(feature = "command_access", issue = "44434")]
990 pub fn get_envs(&self) -> CommandEnvs<'_> {
991 self.inner.get_envs()
994 /// Returns the working directory for the child process.
996 /// This returns [`None`] if the working directory will not be changed.
1001 /// # #![feature(command_access)]
1002 /// use std::path::Path;
1003 /// use std::process::Command;
1005 /// let mut cmd = Command::new("ls");
1006 /// assert_eq!(cmd.get_current_dir(), None);
1007 /// cmd.current_dir("/bin");
1008 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1010 #[unstable(feature = "command_access", issue = "44434")]
1011 pub fn get_current_dir(&self) -> Option<&Path> {
1012 self.inner.get_current_dir()
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl fmt::Debug for Command {
1018 /// Format the program and arguments of a Command for display. Any
1019 /// non-utf8 data is lossily converted using the utf8 replacement
1021 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1026 impl AsInner<imp::Command> for Command {
1027 fn as_inner(&self) -> &imp::Command {
1032 impl AsInnerMut<imp::Command> for Command {
1033 fn as_inner_mut(&mut self) -> &mut imp::Command {
1038 /// An iterator over the command arguments.
1040 /// This struct is created by [`Command::get_args`]. See its documentation for
1042 #[unstable(feature = "command_access", issue = "44434")]
1044 pub struct CommandArgs<'a> {
1045 inner: imp::CommandArgs<'a>,
1048 #[unstable(feature = "command_access", issue = "44434")]
1049 impl<'a> Iterator for CommandArgs<'a> {
1050 type Item = &'a OsStr;
1051 fn next(&mut self) -> Option<&'a OsStr> {
1054 fn size_hint(&self) -> (usize, Option<usize>) {
1055 self.inner.size_hint()
1059 #[unstable(feature = "command_access", issue = "44434")]
1060 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1061 fn len(&self) -> usize {
1064 fn is_empty(&self) -> bool {
1065 self.inner.is_empty()
1069 /// The output of a finished process.
1071 /// This is returned in a Result by either the [`output`] method of a
1072 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1075 /// [`output`]: Command::output
1076 /// [`wait_with_output`]: Child::wait_with_output
1077 #[derive(PartialEq, Eq, Clone)]
1078 #[stable(feature = "process", since = "1.0.0")]
1080 /// The status (exit code) of the process.
1081 #[stable(feature = "process", since = "1.0.0")]
1082 pub status: ExitStatus,
1083 /// The data that the process wrote to stdout.
1084 #[stable(feature = "process", since = "1.0.0")]
1085 pub stdout: Vec<u8>,
1086 /// The data that the process wrote to stderr.
1087 #[stable(feature = "process", since = "1.0.0")]
1088 pub stderr: Vec<u8>,
1091 // If either stderr or stdout are valid utf8 strings it prints the valid
1092 // strings, otherwise it prints the byte sequence instead
1093 #[stable(feature = "process_output_debug", since = "1.7.0")]
1094 impl fmt::Debug for Output {
1095 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 let stdout_utf8 = str::from_utf8(&self.stdout);
1097 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1099 Err(_) => &self.stdout,
1102 let stderr_utf8 = str::from_utf8(&self.stderr);
1103 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1105 Err(_) => &self.stderr,
1108 fmt.debug_struct("Output")
1109 .field("status", &self.status)
1110 .field("stdout", stdout_debug)
1111 .field("stderr", stderr_debug)
1116 /// Describes what to do with a standard I/O stream for a child process when
1117 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1119 /// [`stdin`]: Command::stdin
1120 /// [`stdout`]: Command::stdout
1121 /// [`stderr`]: Command::stderr
1122 #[stable(feature = "process", since = "1.0.0")]
1123 pub struct Stdio(imp::Stdio);
1126 /// A new pipe should be arranged to connect the parent and child processes.
1133 /// use std::process::{Command, Stdio};
1135 /// let output = Command::new("echo")
1136 /// .arg("Hello, world!")
1137 /// .stdout(Stdio::piped())
1139 /// .expect("Failed to execute command");
1141 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1142 /// // Nothing echoed to console
1148 /// use std::io::Write;
1149 /// use std::process::{Command, Stdio};
1151 /// let mut child = Command::new("rev")
1152 /// .stdin(Stdio::piped())
1153 /// .stdout(Stdio::piped())
1155 /// .expect("Failed to spawn child process");
1157 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1158 /// std::thread::spawn(move || {
1159 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1162 /// let output = child.wait_with_output().expect("Failed to read stdout");
1163 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1166 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1167 /// stdout and stderr at the same time may cause a deadlock.
1168 /// This is an issue when running any program that doesn't guarantee that it reads
1169 /// its entire stdin before writing more than a pipe buffer's worth of output.
1170 /// The size of a pipe buffer varies on different targets.
1172 #[stable(feature = "process", since = "1.0.0")]
1173 pub fn piped() -> Stdio {
1174 Stdio(imp::Stdio::MakePipe)
1177 /// The child inherits from the corresponding parent descriptor.
1184 /// use std::process::{Command, Stdio};
1186 /// let output = Command::new("echo")
1187 /// .arg("Hello, world!")
1188 /// .stdout(Stdio::inherit())
1190 /// .expect("Failed to execute command");
1192 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1193 /// // "Hello, world!" echoed to console
1199 /// use std::process::{Command, Stdio};
1200 /// use std::io::{self, Write};
1202 /// let output = Command::new("rev")
1203 /// .stdin(Stdio::inherit())
1204 /// .stdout(Stdio::piped())
1206 /// .expect("Failed to execute command");
1208 /// print!("You piped in the reverse of: ");
1209 /// io::stdout().write_all(&output.stdout).unwrap();
1211 #[stable(feature = "process", since = "1.0.0")]
1212 pub fn inherit() -> Stdio {
1213 Stdio(imp::Stdio::Inherit)
1216 /// This stream will be ignored. This is the equivalent of attaching the
1217 /// stream to `/dev/null`.
1224 /// use std::process::{Command, Stdio};
1226 /// let output = Command::new("echo")
1227 /// .arg("Hello, world!")
1228 /// .stdout(Stdio::null())
1230 /// .expect("Failed to execute command");
1232 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1233 /// // Nothing echoed to console
1239 /// use std::process::{Command, Stdio};
1241 /// let output = Command::new("rev")
1242 /// .stdin(Stdio::null())
1243 /// .stdout(Stdio::piped())
1245 /// .expect("Failed to execute command");
1247 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1248 /// // Ignores any piped-in input
1250 #[stable(feature = "process", since = "1.0.0")]
1251 pub fn null() -> Stdio {
1252 Stdio(imp::Stdio::Null)
1256 impl FromInner<imp::Stdio> for Stdio {
1257 fn from_inner(inner: imp::Stdio) -> Stdio {
1262 #[stable(feature = "std_debug", since = "1.16.0")]
1263 impl fmt::Debug for Stdio {
1264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1265 f.debug_struct("Stdio").finish_non_exhaustive()
1269 #[stable(feature = "stdio_from", since = "1.20.0")]
1270 impl From<ChildStdin> for Stdio {
1271 /// Converts a `ChildStdin` into a `Stdio`
1275 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1278 /// use std::process::{Command, Stdio};
1280 /// let reverse = Command::new("rev")
1281 /// .stdin(Stdio::piped())
1283 /// .expect("failed reverse command");
1285 /// let _echo = Command::new("echo")
1286 /// .arg("Hello, world!")
1287 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1289 /// .expect("failed echo command");
1291 /// // "!dlrow ,olleH" echoed to console
1293 fn from(child: ChildStdin) -> Stdio {
1294 Stdio::from_inner(child.into_inner().into())
1298 #[stable(feature = "stdio_from", since = "1.20.0")]
1299 impl From<ChildStdout> for Stdio {
1300 /// Converts a `ChildStdout` into a `Stdio`
1304 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1307 /// use std::process::{Command, Stdio};
1309 /// let hello = Command::new("echo")
1310 /// .arg("Hello, world!")
1311 /// .stdout(Stdio::piped())
1313 /// .expect("failed echo command");
1315 /// let reverse = Command::new("rev")
1316 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1318 /// .expect("failed reverse command");
1320 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1322 fn from(child: ChildStdout) -> Stdio {
1323 Stdio::from_inner(child.into_inner().into())
1327 #[stable(feature = "stdio_from", since = "1.20.0")]
1328 impl From<ChildStderr> for Stdio {
1329 /// Converts a `ChildStderr` into a `Stdio`
1334 /// use std::process::{Command, Stdio};
1336 /// let reverse = Command::new("rev")
1337 /// .arg("non_existing_file.txt")
1338 /// .stderr(Stdio::piped())
1340 /// .expect("failed reverse command");
1342 /// let cat = Command::new("cat")
1344 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1346 /// .expect("failed echo command");
1349 /// String::from_utf8_lossy(&cat.stdout),
1350 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1353 fn from(child: ChildStderr) -> Stdio {
1354 Stdio::from_inner(child.into_inner().into())
1358 #[stable(feature = "stdio_from", since = "1.20.0")]
1359 impl From<fs::File> for Stdio {
1360 /// Converts a `File` into a `Stdio`
1364 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1367 /// use std::fs::File;
1368 /// use std::process::Command;
1370 /// // With the `foo.txt` file containing `Hello, world!"
1371 /// let file = File::open("foo.txt").unwrap();
1373 /// let reverse = Command::new("rev")
1374 /// .stdin(file) // Implicit File conversion into a Stdio
1376 /// .expect("failed reverse command");
1378 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1380 fn from(file: fs::File) -> Stdio {
1381 Stdio::from_inner(file.into_inner().into())
1385 /// Describes the result of a process after it has terminated.
1387 /// This `struct` is used to represent the exit status or other termination of a child process.
1388 /// Child processes are created via the [`Command`] struct and their exit
1389 /// status is exposed through the [`status`] method, or the [`wait`] method
1390 /// of a [`Child`] process.
1392 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1393 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1395 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1396 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1398 /// [`status`]: Command::status
1399 /// [`wait`]: Child::wait
1400 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1401 #[stable(feature = "process", since = "1.0.0")]
1402 pub struct ExitStatus(imp::ExitStatus);
1404 /// Allows extension traits within `std`.
1405 #[unstable(feature = "sealed", issue = "none")]
1406 impl crate::sealed::Sealed for ExitStatus {}
1409 /// Was termination successful? Returns a `Result`.
1414 /// #![feature(exit_status_error)]
1415 /// # if cfg!(unix) {
1416 /// use std::process::Command;
1418 /// let status = Command::new("ls")
1419 /// .arg("/dev/nonexistent")
1421 /// .expect("ls could not be executed");
1423 /// println!("ls: {}", status);
1424 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1425 /// # } // cfg!(unix)
1427 #[unstable(feature = "exit_status_error", issue = "84908")]
1428 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1429 self.0.exit_ok().map_err(ExitStatusError)
1432 /// Was termination successful? Signal termination is not considered a
1433 /// success, and success is defined as a zero exit status.
1438 /// use std::process::Command;
1440 /// let status = Command::new("mkdir")
1441 /// .arg("projects")
1443 /// .expect("failed to execute mkdir");
1445 /// if status.success() {
1446 /// println!("'projects/' directory created");
1448 /// println!("failed to create 'projects/' directory: {}", status);
1451 #[stable(feature = "process", since = "1.0.0")]
1452 pub fn success(&self) -> bool {
1453 self.0.exit_ok().is_ok()
1456 /// Returns the exit code of the process, if any.
1458 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1459 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1460 /// bits, and that values that didn't come from a program's call to `exit` may be invented the
1461 /// runtime system (often, for example, 255, 254, 127 or 126).
1463 /// On Unix, this will return `None` if the process was terminated by a signal.
1464 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1465 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1470 /// use std::process::Command;
1472 /// let status = Command::new("mkdir")
1473 /// .arg("projects")
1475 /// .expect("failed to execute mkdir");
1477 /// match status.code() {
1478 /// Some(code) => println!("Exited with status code: {}", code),
1479 /// None => println!("Process terminated by signal")
1482 #[stable(feature = "process", since = "1.0.0")]
1483 pub fn code(&self) -> Option<i32> {
1488 impl AsInner<imp::ExitStatus> for ExitStatus {
1489 fn as_inner(&self) -> &imp::ExitStatus {
1494 impl FromInner<imp::ExitStatus> for ExitStatus {
1495 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1500 #[stable(feature = "process", since = "1.0.0")]
1501 impl fmt::Display for ExitStatus {
1502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1507 /// Allows extension traits within `std`.
1508 #[unstable(feature = "sealed", issue = "none")]
1509 impl crate::sealed::Sealed for ExitStatusError {}
1511 /// Describes the result of a process after it has failed
1513 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1518 /// #![feature(exit_status_error)]
1519 /// # if cfg!(unix) {
1520 /// use std::process::{Command, ExitStatusError};
1522 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1523 /// Command::new(cmd).status().unwrap().exit_ok()?;
1527 /// run("true").unwrap();
1528 /// run("false").unwrap_err();
1529 /// # } // cfg!(unix)
1531 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1532 #[unstable(feature = "exit_status_error", issue = "84908")]
1533 // The definition of imp::ExitStatusError should ideally be such that
1534 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1535 pub struct ExitStatusError(imp::ExitStatusError);
1537 #[unstable(feature = "exit_status_error", issue = "84908")]
1538 impl ExitStatusError {
1539 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1541 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1542 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1543 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1544 /// runtime system (often, for example, 255, 254, 127 or 126).
1546 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1547 /// handle such situations specially, consider using methods from
1548 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1550 /// If the process finished by calling `exit` with a nonzero value, this will return
1551 /// that exit status.
1553 /// If the error was something else, it will return `None`.
1555 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1556 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1561 /// #![feature(exit_status_error)]
1562 /// # #[cfg(unix)] {
1563 /// use std::process::Command;
1565 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1566 /// assert_eq!(bad.code(), Some(1));
1567 /// # } // #[cfg(unix)]
1569 pub fn code(&self) -> Option<i32> {
1570 self.code_nonzero().map(Into::into)
1573 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1575 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1577 /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1578 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1579 /// a type-level guarantee of nonzeroness.
1584 /// #![feature(exit_status_error)]
1585 /// # if cfg!(unix) {
1586 /// use std::convert::TryFrom;
1587 /// use std::num::NonZeroI32;
1588 /// use std::process::Command;
1590 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1591 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1592 /// # } // cfg!(unix)
1594 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1598 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1599 pub fn into_status(&self) -> ExitStatus {
1600 ExitStatus(self.0.into())
1604 #[unstable(feature = "exit_status_error", issue = "84908")]
1605 impl Into<ExitStatus> for ExitStatusError {
1606 fn into(self) -> ExitStatus {
1607 ExitStatus(self.0.into())
1611 #[unstable(feature = "exit_status_error", issue = "84908")]
1612 impl fmt::Display for ExitStatusError {
1613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1614 write!(f, "process exited unsuccessfully: {}", self.into_status())
1618 #[unstable(feature = "exit_status_error", issue = "84908")]
1619 impl crate::error::Error for ExitStatusError {}
1621 /// This type represents the status code a process can return to its
1622 /// parent under normal termination.
1624 /// Numeric values used in this type don't have portable meanings, and
1625 /// different platforms may mask different amounts of them.
1627 /// For the platform's canonical successful and unsuccessful codes, see
1628 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1630 /// [`SUCCESS`]: ExitCode::SUCCESS
1631 /// [`FAILURE`]: ExitCode::FAILURE
1633 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1634 /// it was ultimately cut from that RFC, and thus this type is more subject
1635 /// to change even than the usual unstable item churn.
1637 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1638 #[derive(Clone, Copy, Debug)]
1639 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1640 pub struct ExitCode(imp::ExitCode);
1642 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1644 /// The canonical ExitCode for successful termination on this platform.
1646 /// Note that a `()`-returning `main` implicitly results in a successful
1647 /// termination, so there's no need to return this from `main` unless
1648 /// you're also returning other possible codes.
1649 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1650 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1652 /// The canonical ExitCode for unsuccessful termination on this platform.
1654 /// If you're only returning this and `SUCCESS` from `main`, consider
1655 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1656 /// return the same codes (but will also `eprintln!` the error).
1657 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1658 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1662 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1663 /// error is returned.
1665 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1667 /// This is equivalent to sending a SIGKILL on Unix platforms.
1674 /// use std::process::Command;
1676 /// let mut command = Command::new("yes");
1677 /// if let Ok(mut child) = command.spawn() {
1678 /// child.kill().expect("command wasn't running");
1680 /// println!("yes command didn't start");
1684 /// [`ErrorKind`]: io::ErrorKind
1685 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1686 #[stable(feature = "process", since = "1.0.0")]
1687 pub fn kill(&mut self) -> io::Result<()> {
1691 /// Returns the OS-assigned process identifier associated with this child.
1698 /// use std::process::Command;
1700 /// let mut command = Command::new("ls");
1701 /// if let Ok(child) = command.spawn() {
1702 /// println!("Child's ID is {}", child.id());
1704 /// println!("ls command didn't start");
1707 #[stable(feature = "process_id", since = "1.3.0")]
1708 pub fn id(&self) -> u32 {
1712 /// Waits for the child to exit completely, returning the status that it
1713 /// exited with. This function will continue to have the same return value
1714 /// after it has been called at least once.
1716 /// The stdin handle to the child process, if any, will be closed
1717 /// before waiting. This helps avoid deadlock: it ensures that the
1718 /// child does not block waiting for input from the parent, while
1719 /// the parent waits for the child to exit.
1726 /// use std::process::Command;
1728 /// let mut command = Command::new("ls");
1729 /// if let Ok(mut child) = command.spawn() {
1730 /// child.wait().expect("command wasn't running");
1731 /// println!("Child has finished its execution!");
1733 /// println!("ls command didn't start");
1736 #[stable(feature = "process", since = "1.0.0")]
1737 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1738 drop(self.stdin.take());
1739 self.handle.wait().map(ExitStatus)
1742 /// Attempts to collect the exit status of the child if it has already
1745 /// This function will not block the calling thread and will only
1746 /// check to see if the child process has exited or not. If the child has
1747 /// exited then on Unix the process ID is reaped. This function is
1748 /// guaranteed to repeatedly return a successful exit status so long as the
1749 /// child has already exited.
1751 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1752 /// exit status is not available at this time then `Ok(None)` is returned.
1753 /// If an error occurs, then that error is returned.
1755 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1762 /// use std::process::Command;
1764 /// let mut child = Command::new("ls").spawn().unwrap();
1766 /// match child.try_wait() {
1767 /// Ok(Some(status)) => println!("exited with: {}", status),
1769 /// println!("status not ready yet, let's really wait");
1770 /// let res = child.wait();
1771 /// println!("result: {:?}", res);
1773 /// Err(e) => println!("error attempting to wait: {}", e),
1776 #[stable(feature = "process_try_wait", since = "1.18.0")]
1777 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1778 Ok(self.handle.try_wait()?.map(ExitStatus))
1781 /// Simultaneously waits for the child to exit and collect all remaining
1782 /// output on the stdout/stderr handles, returning an `Output`
1785 /// The stdin handle to the child process, if any, will be closed
1786 /// before waiting. This helps avoid deadlock: it ensures that the
1787 /// child does not block waiting for input from the parent, while
1788 /// the parent waits for the child to exit.
1790 /// By default, stdin, stdout and stderr are inherited from the parent.
1791 /// In order to capture the output into this `Result<Output>` it is
1792 /// necessary to create new pipes between parent and child. Use
1793 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1798 /// use std::process::{Command, Stdio};
1800 /// let child = Command::new("/bin/cat")
1801 /// .arg("file.txt")
1802 /// .stdout(Stdio::piped())
1804 /// .expect("failed to execute child");
1806 /// let output = child
1807 /// .wait_with_output()
1808 /// .expect("failed to wait on child");
1810 /// assert!(output.status.success());
1813 #[stable(feature = "process", since = "1.0.0")]
1814 pub fn wait_with_output(mut self) -> io::Result<Output> {
1815 drop(self.stdin.take());
1817 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1818 match (self.stdout.take(), self.stderr.take()) {
1820 (Some(mut out), None) => {
1821 let res = out.read_to_end(&mut stdout);
1824 (None, Some(mut err)) => {
1825 let res = err.read_to_end(&mut stderr);
1828 (Some(out), Some(err)) => {
1829 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1834 let status = self.wait()?;
1835 Ok(Output { status, stdout, stderr })
1839 /// Terminates the current process with the specified exit code.
1841 /// This function will never return and will immediately terminate the current
1842 /// process. The exit code is passed through to the underlying OS and will be
1843 /// available for consumption by another process.
1845 /// Note that because this function never returns, and that it terminates the
1846 /// process, no destructors on the current stack or any other thread's stack
1847 /// will be run. If a clean shutdown is needed it is recommended to only call
1848 /// this function at a known point where there are no more destructors left
1851 /// ## Platform-specific behavior
1853 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1854 /// will be visible to a parent process inspecting the exit code. On most
1855 /// Unix-like platforms, only the eight least-significant bits are considered.
1859 /// Due to this function’s behavior regarding destructors, a conventional way
1860 /// to use the function is to extract the actual computation to another
1861 /// function and compute the exit code from its return value:
1864 /// fn run_app() -> Result<(), ()> {
1865 /// // Application logic here
1870 /// std::process::exit(match run_app() {
1873 /// eprintln!("error: {:?}", err);
1880 /// Due to [platform-specific behavior], the exit code for this example will be
1881 /// `0` on Linux, but `256` on Windows:
1884 /// use std::process;
1886 /// process::exit(0x0100);
1889 /// [platform-specific behavior]: #platform-specific-behavior
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 pub fn exit(code: i32) -> ! {
1892 crate::sys_common::rt::cleanup();
1893 crate::sys::os::exit(code)
1896 /// Terminates the process in an abnormal fashion.
1898 /// The function will never return and will immediately terminate the current
1899 /// process in a platform specific "abnormal" manner.
1901 /// Note that because this function never returns, and that it terminates the
1902 /// process, no destructors on the current stack or any other thread's stack
1905 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
1906 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
1908 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1909 /// the current thread's stack and calls all destructors.
1910 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1911 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1912 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1914 /// If a clean shutdown is needed it is recommended to only call
1915 /// this function at a known point where there are no more destructors left
1918 /// The process's termination will be similar to that from the C `abort()`
1919 /// function. On Unix, the process will terminate with signal `SIGABRT`, which
1920 /// typically means that the shell prints "Aborted".
1925 /// use std::process;
1928 /// println!("aborting");
1930 /// process::abort();
1932 /// // execution never gets here
1936 /// The `abort` function terminates the process, so the destructor will not
1937 /// get run on the example below:
1940 /// use std::process;
1944 /// impl Drop for HasDrop {
1945 /// fn drop(&mut self) {
1946 /// println!("This will never be printed!");
1951 /// let _x = HasDrop;
1952 /// process::abort();
1953 /// // the destructor implemented for HasDrop will never get run
1957 /// [panic hook]: crate::panic::set_hook
1958 #[stable(feature = "process_abort", since = "1.17.0")]
1960 pub fn abort() -> ! {
1961 crate::sys::abort_internal();
1964 /// Returns the OS-assigned process identifier associated with this process.
1971 /// use std::process;
1973 /// println!("My pid is {}", process::id());
1977 #[stable(feature = "getpid", since = "1.26.0")]
1978 pub fn id() -> u32 {
1979 crate::sys::os::getpid()
1982 /// A trait for implementing arbitrary return types in the `main` function.
1984 /// The C-main function only supports to return integers as return type.
1985 /// So, every type implementing the `Termination` trait has to be converted
1988 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1989 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1990 #[cfg_attr(not(test), lang = "termination")]
1991 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1992 #[rustc_on_unimplemented(
1993 message = "`main` has invalid return type `{Self}`",
1994 label = "`main` can only return types that implement `{Termination}`"
1996 pub trait Termination {
1997 /// Is called to get the representation of the value as status code.
1998 /// This status code is returned to the operating system.
1999 fn report(self) -> i32;
2002 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2003 impl Termination for () {
2005 fn report(self) -> i32 {
2006 ExitCode::SUCCESS.report()
2010 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2011 impl<E: fmt::Debug> Termination for Result<(), E> {
2012 fn report(self) -> i32 {
2014 Ok(()) => ().report(),
2015 Err(err) => Err::<!, _>(err).report(),
2020 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2021 impl Termination for ! {
2022 fn report(self) -> i32 {
2027 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2028 impl<E: fmt::Debug> Termination for Result<!, E> {
2029 fn report(self) -> i32 {
2030 let Err(err) = self;
2031 eprintln!("Error: {:?}", err);
2032 ExitCode::FAILURE.report()
2036 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2037 impl Termination for ExitCode {
2039 fn report(self) -> i32 {