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::convert::Infallible;
110 use crate::ffi::OsStr;
113 use crate::io::{self, IoSlice, IoSliceMut};
114 use crate::num::NonZeroI32;
115 use crate::path::Path;
117 use crate::sys::pipe::{read2, AnonPipe};
118 use crate::sys::process as imp;
119 #[stable(feature = "command_access", since = "1.57.0")]
120 pub use crate::sys_common::process::CommandEnvs;
121 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
123 /// Representation of a running or exited child process.
125 /// This structure is used to represent and manage child processes. A child
126 /// process is created via the [`Command`] struct, which configures the
127 /// spawning process and can itself be constructed using a builder-style
130 /// There is no implementation of [`Drop`] for child processes,
131 /// so if you do not ensure the `Child` has exited then it will continue to
132 /// run, even after the `Child` handle to the child process has gone out of
135 /// Calling [`wait`] (or other functions that wrap around it) will make
136 /// the parent process wait until the child has actually exited before
141 /// On some systems, calling [`wait`] or similar is necessary for the OS to
142 /// release resources. A process that terminated but has not been waited on is
143 /// still around as a "zombie". Leaving too many zombies around may exhaust
144 /// global resources (for example process IDs).
146 /// The standard library does *not* automatically wait on child processes (not
147 /// even if the `Child` is dropped), it is up to the application developer to do
148 /// so. As a consequence, dropping `Child` handles without waiting on them first
149 /// is not recommended in long-running applications.
154 /// use std::process::Command;
156 /// let mut child = Command::new("/bin/cat")
159 /// .expect("failed to execute child");
161 /// let ecode = child.wait()
162 /// .expect("failed to wait on child");
164 /// assert!(ecode.success());
167 /// [`wait`]: Child::wait
168 #[stable(feature = "process", since = "1.0.0")]
170 pub(crate) handle: imp::Process,
172 /// The handle for writing to the child's standard input (stdin), if it has
173 /// been captured. To avoid partially moving
174 /// the `child` and thus blocking yourself from calling
175 /// functions on `child` while using `stdin`,
176 /// you might find it helpful:
178 /// ```compile_fail,E0425
179 /// let stdin = child.stdin.take().unwrap();
181 #[stable(feature = "process", since = "1.0.0")]
182 pub stdin: Option<ChildStdin>,
184 /// The handle for reading from the child's standard output (stdout), if it
185 /// has been captured. You might find it helpful to do
187 /// ```compile_fail,E0425
188 /// let stdout = child.stdout.take().unwrap();
191 /// to avoid partially moving the `child` and thus blocking yourself from calling
192 /// functions on `child` while using `stdout`.
193 #[stable(feature = "process", since = "1.0.0")]
194 pub stdout: Option<ChildStdout>,
196 /// The handle for reading from the child's standard error (stderr), if it
197 /// has been captured. You might find it helpful to do
199 /// ```compile_fail,E0425
200 /// let stderr = child.stderr.take().unwrap();
203 /// to avoid partially moving the `child` and thus blocking yourself from calling
204 /// functions on `child` while using `stderr`.
205 #[stable(feature = "process", since = "1.0.0")]
206 pub stderr: Option<ChildStderr>,
209 /// Allows extension traits within `std`.
210 #[unstable(feature = "sealed", issue = "none")]
211 impl crate::sealed::Sealed for Child {}
213 impl AsInner<imp::Process> for Child {
214 fn as_inner(&self) -> &imp::Process {
219 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
220 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
223 stdin: io.stdin.map(ChildStdin::from_inner),
224 stdout: io.stdout.map(ChildStdout::from_inner),
225 stderr: io.stderr.map(ChildStderr::from_inner),
230 impl IntoInner<imp::Process> for Child {
231 fn into_inner(self) -> imp::Process {
236 #[stable(feature = "std_debug", since = "1.16.0")]
237 impl fmt::Debug for Child {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 f.debug_struct("Child")
240 .field("stdin", &self.stdin)
241 .field("stdout", &self.stdout)
242 .field("stderr", &self.stderr)
243 .finish_non_exhaustive()
247 /// A handle to a child process's standard input (stdin).
249 /// This struct is used in the [`stdin`] field on [`Child`].
251 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
252 /// file handle will be closed. If the child process was blocked on input prior
253 /// to being dropped, it will become unblocked after dropping.
255 /// [`stdin`]: Child::stdin
257 #[stable(feature = "process", since = "1.0.0")]
258 pub struct ChildStdin {
262 // In addition to the `impl`s here, `ChildStdin` also has `impl`s for
263 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
264 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
265 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
266 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
268 #[stable(feature = "process", since = "1.0.0")]
269 impl Write for ChildStdin {
270 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
274 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
275 (&*self).write_vectored(bufs)
278 fn is_write_vectored(&self) -> bool {
279 io::Write::is_write_vectored(&&*self)
282 fn flush(&mut self) -> io::Result<()> {
287 #[stable(feature = "write_mt", since = "1.48.0")]
288 impl Write for &ChildStdin {
289 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
290 self.inner.write(buf)
293 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
294 self.inner.write_vectored(bufs)
297 fn is_write_vectored(&self) -> bool {
298 self.inner.is_write_vectored()
301 fn flush(&mut self) -> io::Result<()> {
306 impl AsInner<AnonPipe> for ChildStdin {
307 fn as_inner(&self) -> &AnonPipe {
312 impl IntoInner<AnonPipe> for ChildStdin {
313 fn into_inner(self) -> AnonPipe {
318 impl FromInner<AnonPipe> for ChildStdin {
319 fn from_inner(pipe: AnonPipe) -> ChildStdin {
320 ChildStdin { inner: pipe }
324 #[stable(feature = "std_debug", since = "1.16.0")]
325 impl fmt::Debug for ChildStdin {
326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327 f.debug_struct("ChildStdin").finish_non_exhaustive()
331 /// A handle to a child process's standard output (stdout).
333 /// This struct is used in the [`stdout`] field on [`Child`].
335 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
336 /// underlying file handle will be closed.
338 /// [`stdout`]: Child::stdout
340 #[stable(feature = "process", since = "1.0.0")]
341 pub struct ChildStdout {
345 // In addition to the `impl`s here, `ChildStdout` also has `impl`s for
346 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
347 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
348 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
349 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
351 #[stable(feature = "process", since = "1.0.0")]
352 impl Read for ChildStdout {
353 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
357 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
358 self.inner.read_vectored(bufs)
362 fn is_read_vectored(&self) -> bool {
363 self.inner.is_read_vectored()
367 impl AsInner<AnonPipe> for ChildStdout {
368 fn as_inner(&self) -> &AnonPipe {
373 impl IntoInner<AnonPipe> for ChildStdout {
374 fn into_inner(self) -> AnonPipe {
379 impl FromInner<AnonPipe> for ChildStdout {
380 fn from_inner(pipe: AnonPipe) -> ChildStdout {
381 ChildStdout { inner: pipe }
385 #[stable(feature = "std_debug", since = "1.16.0")]
386 impl fmt::Debug for ChildStdout {
387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388 f.debug_struct("ChildStdout").finish_non_exhaustive()
392 /// A handle to a child process's stderr.
394 /// This struct is used in the [`stderr`] field on [`Child`].
396 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
397 /// underlying file handle will be closed.
399 /// [`stderr`]: Child::stderr
401 #[stable(feature = "process", since = "1.0.0")]
402 pub struct ChildStderr {
406 // In addition to the `impl`s here, `ChildStderr` also has `impl`s for
407 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
408 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
409 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
410 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
412 #[stable(feature = "process", since = "1.0.0")]
413 impl Read for ChildStderr {
414 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
418 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
419 self.inner.read_vectored(bufs)
423 fn is_read_vectored(&self) -> bool {
424 self.inner.is_read_vectored()
428 impl AsInner<AnonPipe> for ChildStderr {
429 fn as_inner(&self) -> &AnonPipe {
434 impl IntoInner<AnonPipe> for ChildStderr {
435 fn into_inner(self) -> AnonPipe {
440 impl FromInner<AnonPipe> for ChildStderr {
441 fn from_inner(pipe: AnonPipe) -> ChildStderr {
442 ChildStderr { inner: pipe }
446 #[stable(feature = "std_debug", since = "1.16.0")]
447 impl fmt::Debug for ChildStderr {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 f.debug_struct("ChildStderr").finish_non_exhaustive()
453 /// A process builder, providing fine-grained control
454 /// over how a new process should be spawned.
456 /// A default configuration can be
457 /// generated using `Command::new(program)`, where `program` gives a path to the
458 /// program to be executed. Additional builder methods allow the configuration
459 /// to be changed (for example, by adding arguments) prior to spawning:
462 /// use std::process::Command;
464 /// let output = if cfg!(target_os = "windows") {
465 /// Command::new("cmd")
466 /// .args(["/C", "echo hello"])
468 /// .expect("failed to execute process")
470 /// Command::new("sh")
472 /// .arg("echo hello")
474 /// .expect("failed to execute process")
477 /// let hello = output.stdout;
480 /// `Command` can be reused to spawn multiple processes. The builder methods
481 /// change the command without needing to immediately spawn the process.
484 /// use std::process::Command;
486 /// let mut echo_hello = Command::new("sh");
487 /// echo_hello.arg("-c")
488 /// .arg("echo hello");
489 /// let hello_1 = echo_hello.output().expect("failed to execute process");
490 /// let hello_2 = echo_hello.output().expect("failed to execute process");
493 /// Similarly, you can call builder methods after spawning a process and then
494 /// spawn a new process with the modified settings.
497 /// use std::process::Command;
499 /// let mut list_dir = Command::new("ls");
501 /// // Execute `ls` in the current directory of the program.
502 /// list_dir.status().expect("process failed to execute");
506 /// // Change `ls` to execute in the root directory.
507 /// list_dir.current_dir("/");
509 /// // And then execute `ls` again but in the root directory.
510 /// list_dir.status().expect("process failed to execute");
512 #[stable(feature = "process", since = "1.0.0")]
517 /// Allows extension traits within `std`.
518 #[unstable(feature = "sealed", issue = "none")]
519 impl crate::sealed::Sealed for Command {}
522 /// Constructs a new `Command` for launching the program at
523 /// path `program`, with the following default configuration:
525 /// * No arguments to the program
526 /// * Inherit the current process's environment
527 /// * Inherit the current process's working directory
528 /// * Inherit stdin/stdout/stderr for [`spawn`] or [`status`], but create pipes for [`output`]
530 /// [`spawn`]: Self::spawn
531 /// [`status`]: Self::status
532 /// [`output`]: Self::output
534 /// Builder methods are provided to change these defaults and
535 /// otherwise configure the process.
537 /// If `program` is not an absolute path, the `PATH` will be searched in
538 /// an OS-defined way.
540 /// The search path to be used may be controlled by setting the
541 /// `PATH` environment variable on the Command,
542 /// but this has some implementation limitations on Windows
543 /// (see issue #37519).
550 /// use std::process::Command;
552 /// Command::new("sh")
554 /// .expect("sh command failed to start");
556 #[stable(feature = "process", since = "1.0.0")]
557 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
558 Command { inner: imp::Command::new(program.as_ref()) }
561 /// Adds an argument to pass to the program.
563 /// Only one argument can be passed per use. So instead of:
566 /// # std::process::Command::new("sh")
567 /// .arg("-C /path/to/repo")
574 /// # std::process::Command::new("sh")
576 /// .arg("/path/to/repo")
580 /// To pass multiple arguments see [`args`].
582 /// [`args`]: Command::args
584 /// Note that the argument is not passed through a shell, but given
585 /// literally to the program. This means that shell syntax like quotes,
586 /// escaped characters, word splitting, glob patterns, substitution, etc.
594 /// use std::process::Command;
596 /// Command::new("ls")
600 /// .expect("ls command failed to start");
602 #[stable(feature = "process", since = "1.0.0")]
603 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
604 self.inner.arg(arg.as_ref());
608 /// Adds multiple arguments to pass to the program.
610 /// To pass a single argument see [`arg`].
612 /// [`arg`]: Command::arg
614 /// Note that the arguments are not passed through a shell, but given
615 /// literally to the program. This means that shell syntax like quotes,
616 /// escaped characters, word splitting, glob patterns, substitution, etc.
624 /// use std::process::Command;
626 /// Command::new("ls")
627 /// .args(["-l", "-a"])
629 /// .expect("ls command failed to start");
631 #[stable(feature = "process", since = "1.0.0")]
632 pub fn args<I, S>(&mut self, args: I) -> &mut Command
634 I: IntoIterator<Item = S>,
638 self.arg(arg.as_ref());
643 /// Inserts or updates an environment variable mapping.
645 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
646 /// and case-sensitive on all other platforms.
653 /// use std::process::Command;
655 /// Command::new("ls")
656 /// .env("PATH", "/bin")
658 /// .expect("ls command failed to start");
660 #[stable(feature = "process", since = "1.0.0")]
661 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
666 self.inner.env_mut().set(key.as_ref(), val.as_ref());
670 /// Adds or updates multiple environment variable mappings.
677 /// use std::process::{Command, Stdio};
679 /// use std::collections::HashMap;
681 /// let filtered_env : HashMap<String, String> =
682 /// env::vars().filter(|&(ref k, _)|
683 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
686 /// Command::new("printenv")
687 /// .stdin(Stdio::null())
688 /// .stdout(Stdio::inherit())
690 /// .envs(&filtered_env)
692 /// .expect("printenv failed to start");
694 #[stable(feature = "command_envs", since = "1.19.0")]
695 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
697 I: IntoIterator<Item = (K, V)>,
701 for (ref key, ref val) in vars {
702 self.inner.env_mut().set(key.as_ref(), val.as_ref());
707 /// Removes an environment variable mapping.
714 /// use std::process::Command;
716 /// Command::new("ls")
717 /// .env_remove("PATH")
719 /// .expect("ls command failed to start");
721 #[stable(feature = "process", since = "1.0.0")]
722 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
723 self.inner.env_mut().remove(key.as_ref());
727 /// Clears the entire environment map for the child process.
734 /// use std::process::Command;
736 /// Command::new("ls")
739 /// .expect("ls command failed to start");
741 #[stable(feature = "process", since = "1.0.0")]
742 pub fn env_clear(&mut self) -> &mut Command {
743 self.inner.env_mut().clear();
747 /// Sets the working directory for the child process.
749 /// # Platform-specific behavior
751 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
752 /// whether it should be interpreted relative to the parent's working
753 /// directory or relative to `current_dir`. The behavior in this case is
754 /// platform specific and unstable, and it's recommended to use
755 /// [`canonicalize`] to get an absolute program path instead.
762 /// use std::process::Command;
764 /// Command::new("ls")
765 /// .current_dir("/bin")
767 /// .expect("ls command failed to start");
770 /// [`canonicalize`]: crate::fs::canonicalize
771 #[stable(feature = "process", since = "1.0.0")]
772 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
773 self.inner.cwd(dir.as_ref().as_ref());
777 /// Configuration for the child process's standard input (stdin) handle.
779 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
780 /// defaults to [`piped`] when used with [`output`].
782 /// [`inherit`]: Stdio::inherit
783 /// [`piped`]: Stdio::piped
784 /// [`spawn`]: Self::spawn
785 /// [`status`]: Self::status
786 /// [`output`]: Self::output
793 /// use std::process::{Command, Stdio};
795 /// Command::new("ls")
796 /// .stdin(Stdio::null())
798 /// .expect("ls command failed to start");
800 #[stable(feature = "process", since = "1.0.0")]
801 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
802 self.inner.stdin(cfg.into().0);
806 /// Configuration for the child process's standard output (stdout) handle.
808 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
809 /// defaults to [`piped`] when used with [`output`].
811 /// [`inherit`]: Stdio::inherit
812 /// [`piped`]: Stdio::piped
813 /// [`spawn`]: Self::spawn
814 /// [`status`]: Self::status
815 /// [`output`]: Self::output
822 /// use std::process::{Command, Stdio};
824 /// Command::new("ls")
825 /// .stdout(Stdio::null())
827 /// .expect("ls command failed to start");
829 #[stable(feature = "process", since = "1.0.0")]
830 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
831 self.inner.stdout(cfg.into().0);
835 /// Configuration for the child process's standard error (stderr) handle.
837 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
838 /// defaults to [`piped`] when used with [`output`].
840 /// [`inherit`]: Stdio::inherit
841 /// [`piped`]: Stdio::piped
842 /// [`spawn`]: Self::spawn
843 /// [`status`]: Self::status
844 /// [`output`]: Self::output
851 /// use std::process::{Command, Stdio};
853 /// Command::new("ls")
854 /// .stderr(Stdio::null())
856 /// .expect("ls command failed to start");
858 #[stable(feature = "process", since = "1.0.0")]
859 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
860 self.inner.stderr(cfg.into().0);
864 /// Executes the command as a child process, returning a handle to it.
866 /// By default, stdin, stdout and stderr are inherited from the parent.
873 /// use std::process::Command;
875 /// Command::new("ls")
877 /// .expect("ls command failed to start");
879 #[stable(feature = "process", since = "1.0.0")]
880 pub fn spawn(&mut self) -> io::Result<Child> {
881 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
884 /// Executes the command as a child process, waiting for it to finish and
885 /// collecting all of its output.
887 /// By default, stdout and stderr are captured (and used to provide the
888 /// resulting output). Stdin is not inherited from the parent and any
889 /// attempt by the child process to read from the stdin stream will result
890 /// in the stream immediately closing.
895 /// use std::process::Command;
896 /// use std::io::{self, Write};
897 /// let output = Command::new("/bin/cat")
900 /// .expect("failed to execute process");
902 /// println!("status: {}", output.status);
903 /// io::stdout().write_all(&output.stdout).unwrap();
904 /// io::stderr().write_all(&output.stderr).unwrap();
906 /// assert!(output.status.success());
908 #[stable(feature = "process", since = "1.0.0")]
909 pub fn output(&mut self) -> io::Result<Output> {
911 .spawn(imp::Stdio::MakePipe, false)
912 .map(Child::from_inner)
913 .and_then(|p| p.wait_with_output())
916 /// Executes a command as a child process, waiting for it to finish and
917 /// collecting its status.
919 /// By default, stdin, stdout and stderr are inherited from the parent.
924 /// use std::process::Command;
926 /// let status = Command::new("/bin/cat")
929 /// .expect("failed to execute process");
931 /// println!("process finished with: {status}");
933 /// assert!(status.success());
935 #[stable(feature = "process", since = "1.0.0")]
936 pub fn status(&mut self) -> io::Result<ExitStatus> {
938 .spawn(imp::Stdio::Inherit, true)
939 .map(Child::from_inner)
940 .and_then(|mut p| p.wait())
943 /// Returns the path to the program that was given to [`Command::new`].
948 /// use std::process::Command;
950 /// let cmd = Command::new("echo");
951 /// assert_eq!(cmd.get_program(), "echo");
954 #[stable(feature = "command_access", since = "1.57.0")]
955 pub fn get_program(&self) -> &OsStr {
956 self.inner.get_program()
959 /// Returns an iterator of the arguments that will be passed to the program.
961 /// This does not include the path to the program as the first argument;
962 /// it only includes the arguments specified with [`Command::arg`] and
963 /// [`Command::args`].
968 /// use std::ffi::OsStr;
969 /// use std::process::Command;
971 /// let mut cmd = Command::new("echo");
972 /// cmd.arg("first").arg("second");
973 /// let args: Vec<&OsStr> = cmd.get_args().collect();
974 /// assert_eq!(args, &["first", "second"]);
976 #[stable(feature = "command_access", since = "1.57.0")]
977 pub fn get_args(&self) -> CommandArgs<'_> {
978 CommandArgs { inner: self.inner.get_args() }
981 /// Returns an iterator of the environment variables that will be set when
982 /// the process is spawned.
984 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
985 /// value is the key, and the second is the value, which is [`None`] if
986 /// the environment variable is to be explicitly removed.
988 /// This only includes environment variables explicitly set with
989 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
990 /// does not include environment variables that will be inherited by the
996 /// use std::ffi::OsStr;
997 /// use std::process::Command;
999 /// let mut cmd = Command::new("ls");
1000 /// cmd.env("TERM", "dumb").env_remove("TZ");
1001 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1002 /// assert_eq!(envs, &[
1003 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1004 /// (OsStr::new("TZ"), None)
1007 #[stable(feature = "command_access", since = "1.57.0")]
1008 pub fn get_envs(&self) -> CommandEnvs<'_> {
1009 self.inner.get_envs()
1012 /// Returns the working directory for the child process.
1014 /// This returns [`None`] if the working directory will not be changed.
1019 /// use std::path::Path;
1020 /// use std::process::Command;
1022 /// let mut cmd = Command::new("ls");
1023 /// assert_eq!(cmd.get_current_dir(), None);
1024 /// cmd.current_dir("/bin");
1025 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1028 #[stable(feature = "command_access", since = "1.57.0")]
1029 pub fn get_current_dir(&self) -> Option<&Path> {
1030 self.inner.get_current_dir()
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl fmt::Debug for Command {
1036 /// Format the program and arguments of a Command for display. Any
1037 /// non-utf8 data is lossily converted using the utf8 replacement
1039 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044 impl AsInner<imp::Command> for Command {
1045 fn as_inner(&self) -> &imp::Command {
1050 impl AsInnerMut<imp::Command> for Command {
1051 fn as_inner_mut(&mut self) -> &mut imp::Command {
1056 /// An iterator over the command arguments.
1058 /// This struct is created by [`Command::get_args`]. See its documentation for
1060 #[must_use = "iterators are lazy and do nothing unless consumed"]
1061 #[stable(feature = "command_access", since = "1.57.0")]
1063 pub struct CommandArgs<'a> {
1064 inner: imp::CommandArgs<'a>,
1067 #[stable(feature = "command_access", since = "1.57.0")]
1068 impl<'a> Iterator for CommandArgs<'a> {
1069 type Item = &'a OsStr;
1070 fn next(&mut self) -> Option<&'a OsStr> {
1073 fn size_hint(&self) -> (usize, Option<usize>) {
1074 self.inner.size_hint()
1078 #[stable(feature = "command_access", since = "1.57.0")]
1079 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1080 fn len(&self) -> usize {
1083 fn is_empty(&self) -> bool {
1084 self.inner.is_empty()
1088 /// The output of a finished process.
1090 /// This is returned in a Result by either the [`output`] method of a
1091 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1094 /// [`output`]: Command::output
1095 /// [`wait_with_output`]: Child::wait_with_output
1096 #[derive(PartialEq, Eq, Clone)]
1097 #[stable(feature = "process", since = "1.0.0")]
1099 /// The status (exit code) of the process.
1100 #[stable(feature = "process", since = "1.0.0")]
1101 pub status: ExitStatus,
1102 /// The data that the process wrote to stdout.
1103 #[stable(feature = "process", since = "1.0.0")]
1104 pub stdout: Vec<u8>,
1105 /// The data that the process wrote to stderr.
1106 #[stable(feature = "process", since = "1.0.0")]
1107 pub stderr: Vec<u8>,
1110 // If either stderr or stdout are valid utf8 strings it prints the valid
1111 // strings, otherwise it prints the byte sequence instead
1112 #[stable(feature = "process_output_debug", since = "1.7.0")]
1113 impl fmt::Debug for Output {
1114 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1115 let stdout_utf8 = str::from_utf8(&self.stdout);
1116 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1118 Err(_) => &self.stdout,
1121 let stderr_utf8 = str::from_utf8(&self.stderr);
1122 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1124 Err(_) => &self.stderr,
1127 fmt.debug_struct("Output")
1128 .field("status", &self.status)
1129 .field("stdout", stdout_debug)
1130 .field("stderr", stderr_debug)
1135 /// Describes what to do with a standard I/O stream for a child process when
1136 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1138 /// [`stdin`]: Command::stdin
1139 /// [`stdout`]: Command::stdout
1140 /// [`stderr`]: Command::stderr
1141 #[stable(feature = "process", since = "1.0.0")]
1142 pub struct Stdio(imp::Stdio);
1145 /// A new pipe should be arranged to connect the parent and child processes.
1152 /// use std::process::{Command, Stdio};
1154 /// let output = Command::new("echo")
1155 /// .arg("Hello, world!")
1156 /// .stdout(Stdio::piped())
1158 /// .expect("Failed to execute command");
1160 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1161 /// // Nothing echoed to console
1167 /// use std::io::Write;
1168 /// use std::process::{Command, Stdio};
1170 /// let mut child = Command::new("rev")
1171 /// .stdin(Stdio::piped())
1172 /// .stdout(Stdio::piped())
1174 /// .expect("Failed to spawn child process");
1176 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1177 /// std::thread::spawn(move || {
1178 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1181 /// let output = child.wait_with_output().expect("Failed to read stdout");
1182 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1185 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1186 /// stdout and stderr at the same time may cause a deadlock.
1187 /// This is an issue when running any program that doesn't guarantee that it reads
1188 /// its entire stdin before writing more than a pipe buffer's worth of output.
1189 /// The size of a pipe buffer varies on different targets.
1192 #[stable(feature = "process", since = "1.0.0")]
1193 pub fn piped() -> Stdio {
1194 Stdio(imp::Stdio::MakePipe)
1197 /// The child inherits from the corresponding parent descriptor.
1204 /// use std::process::{Command, Stdio};
1206 /// let output = Command::new("echo")
1207 /// .arg("Hello, world!")
1208 /// .stdout(Stdio::inherit())
1210 /// .expect("Failed to execute command");
1212 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1213 /// // "Hello, world!" echoed to console
1219 /// use std::process::{Command, Stdio};
1220 /// use std::io::{self, Write};
1222 /// let output = Command::new("rev")
1223 /// .stdin(Stdio::inherit())
1224 /// .stdout(Stdio::piped())
1226 /// .expect("Failed to execute command");
1228 /// print!("You piped in the reverse of: ");
1229 /// io::stdout().write_all(&output.stdout).unwrap();
1232 #[stable(feature = "process", since = "1.0.0")]
1233 pub fn inherit() -> Stdio {
1234 Stdio(imp::Stdio::Inherit)
1237 /// This stream will be ignored. This is the equivalent of attaching the
1238 /// stream to `/dev/null`.
1245 /// use std::process::{Command, Stdio};
1247 /// let output = Command::new("echo")
1248 /// .arg("Hello, world!")
1249 /// .stdout(Stdio::null())
1251 /// .expect("Failed to execute command");
1253 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1254 /// // Nothing echoed to console
1260 /// use std::process::{Command, Stdio};
1262 /// let output = Command::new("rev")
1263 /// .stdin(Stdio::null())
1264 /// .stdout(Stdio::piped())
1266 /// .expect("Failed to execute command");
1268 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1269 /// // Ignores any piped-in input
1272 #[stable(feature = "process", since = "1.0.0")]
1273 pub fn null() -> Stdio {
1274 Stdio(imp::Stdio::Null)
1278 impl FromInner<imp::Stdio> for Stdio {
1279 fn from_inner(inner: imp::Stdio) -> Stdio {
1284 #[stable(feature = "std_debug", since = "1.16.0")]
1285 impl fmt::Debug for Stdio {
1286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1287 f.debug_struct("Stdio").finish_non_exhaustive()
1291 #[stable(feature = "stdio_from", since = "1.20.0")]
1292 impl From<ChildStdin> for Stdio {
1293 /// Converts a [`ChildStdin`] into a [`Stdio`].
1297 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1300 /// use std::process::{Command, Stdio};
1302 /// let reverse = Command::new("rev")
1303 /// .stdin(Stdio::piped())
1305 /// .expect("failed reverse command");
1307 /// let _echo = Command::new("echo")
1308 /// .arg("Hello, world!")
1309 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1311 /// .expect("failed echo command");
1313 /// // "!dlrow ,olleH" echoed to console
1315 fn from(child: ChildStdin) -> Stdio {
1316 Stdio::from_inner(child.into_inner().into())
1320 #[stable(feature = "stdio_from", since = "1.20.0")]
1321 impl From<ChildStdout> for Stdio {
1322 /// Converts a [`ChildStdout`] into a [`Stdio`].
1326 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1329 /// use std::process::{Command, Stdio};
1331 /// let hello = Command::new("echo")
1332 /// .arg("Hello, world!")
1333 /// .stdout(Stdio::piped())
1335 /// .expect("failed echo command");
1337 /// let reverse = Command::new("rev")
1338 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1340 /// .expect("failed reverse command");
1342 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1344 fn from(child: ChildStdout) -> Stdio {
1345 Stdio::from_inner(child.into_inner().into())
1349 #[stable(feature = "stdio_from", since = "1.20.0")]
1350 impl From<ChildStderr> for Stdio {
1351 /// Converts a [`ChildStderr`] into a [`Stdio`].
1356 /// use std::process::{Command, Stdio};
1358 /// let reverse = Command::new("rev")
1359 /// .arg("non_existing_file.txt")
1360 /// .stderr(Stdio::piped())
1362 /// .expect("failed reverse command");
1364 /// let cat = Command::new("cat")
1366 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1368 /// .expect("failed echo command");
1371 /// String::from_utf8_lossy(&cat.stdout),
1372 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1375 fn from(child: ChildStderr) -> Stdio {
1376 Stdio::from_inner(child.into_inner().into())
1380 #[stable(feature = "stdio_from", since = "1.20.0")]
1381 impl From<fs::File> for Stdio {
1382 /// Converts a [`File`](fs::File) into a [`Stdio`].
1386 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1389 /// use std::fs::File;
1390 /// use std::process::Command;
1392 /// // With the `foo.txt` file containing `Hello, world!"
1393 /// let file = File::open("foo.txt").unwrap();
1395 /// let reverse = Command::new("rev")
1396 /// .stdin(file) // Implicit File conversion into a Stdio
1398 /// .expect("failed reverse command");
1400 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1402 fn from(file: fs::File) -> Stdio {
1403 Stdio::from_inner(file.into_inner().into())
1407 /// Describes the result of a process after it has terminated.
1409 /// This `struct` is used to represent the exit status or other termination of a child process.
1410 /// Child processes are created via the [`Command`] struct and their exit
1411 /// status is exposed through the [`status`] method, or the [`wait`] method
1412 /// of a [`Child`] process.
1414 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1415 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1417 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1418 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1420 /// # Differences from `ExitCode`
1422 /// [`ExitCode`] is intended for terminating the currently running process, via
1423 /// the `Termination` trait, in contrast to `ExitStatus`, which represents the
1424 /// termination of a child process. These APIs are separate due to platform
1425 /// compatibility differences and their expected usage; it is not generally
1426 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1427 /// process after the fact.
1429 /// [`status`]: Command::status
1430 /// [`wait`]: Child::wait
1432 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1433 // vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1434 // matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1435 // mean an underlying system call such as `_exit`.
1436 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1437 #[stable(feature = "process", since = "1.0.0")]
1438 pub struct ExitStatus(imp::ExitStatus);
1440 /// Allows extension traits within `std`.
1441 #[unstable(feature = "sealed", issue = "none")]
1442 impl crate::sealed::Sealed for ExitStatus {}
1445 /// Was termination successful? Returns a `Result`.
1450 /// #![feature(exit_status_error)]
1451 /// # if cfg!(unix) {
1452 /// use std::process::Command;
1454 /// let status = Command::new("ls")
1455 /// .arg("/dev/nonexistent")
1457 /// .expect("ls could not be executed");
1459 /// println!("ls: {status}");
1460 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1461 /// # } // cfg!(unix)
1463 #[unstable(feature = "exit_status_error", issue = "84908")]
1464 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1465 self.0.exit_ok().map_err(ExitStatusError)
1468 /// Was termination successful? Signal termination is not considered a
1469 /// success, and success is defined as a zero exit status.
1474 /// use std::process::Command;
1476 /// let status = Command::new("mkdir")
1477 /// .arg("projects")
1479 /// .expect("failed to execute mkdir");
1481 /// if status.success() {
1482 /// println!("'projects/' directory created");
1484 /// println!("failed to create 'projects/' directory: {status}");
1488 #[stable(feature = "process", since = "1.0.0")]
1489 pub fn success(&self) -> bool {
1490 self.0.exit_ok().is_ok()
1493 /// Returns the exit code of the process, if any.
1495 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1496 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1497 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1498 /// runtime system (often, for example, 255, 254, 127 or 126).
1500 /// On Unix, this will return `None` if the process was terminated by a signal.
1501 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1502 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1507 /// use std::process::Command;
1509 /// let status = Command::new("mkdir")
1510 /// .arg("projects")
1512 /// .expect("failed to execute mkdir");
1514 /// match status.code() {
1515 /// Some(code) => println!("Exited with status code: {code}"),
1516 /// None => println!("Process terminated by signal")
1520 #[stable(feature = "process", since = "1.0.0")]
1521 pub fn code(&self) -> Option<i32> {
1526 impl AsInner<imp::ExitStatus> for ExitStatus {
1527 fn as_inner(&self) -> &imp::ExitStatus {
1532 impl FromInner<imp::ExitStatus> for ExitStatus {
1533 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1538 #[stable(feature = "process", since = "1.0.0")]
1539 impl fmt::Display for ExitStatus {
1540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1545 /// Allows extension traits within `std`.
1546 #[unstable(feature = "sealed", issue = "none")]
1547 impl crate::sealed::Sealed for ExitStatusError {}
1549 /// Describes the result of a process after it has failed
1551 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1556 /// #![feature(exit_status_error)]
1557 /// # if cfg!(unix) {
1558 /// use std::process::{Command, ExitStatusError};
1560 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1561 /// Command::new(cmd).status().unwrap().exit_ok()?;
1565 /// run("true").unwrap();
1566 /// run("false").unwrap_err();
1567 /// # } // cfg!(unix)
1569 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1570 #[unstable(feature = "exit_status_error", issue = "84908")]
1571 // The definition of imp::ExitStatusError should ideally be such that
1572 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1573 pub struct ExitStatusError(imp::ExitStatusError);
1575 #[unstable(feature = "exit_status_error", issue = "84908")]
1576 impl ExitStatusError {
1577 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1579 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1580 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1581 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1582 /// runtime system (often, for example, 255, 254, 127 or 126).
1584 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1585 /// handle such situations specially, consider using methods from
1586 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1588 /// If the process finished by calling `exit` with a nonzero value, this will return
1589 /// that exit status.
1591 /// If the error was something else, it will return `None`.
1593 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1594 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1599 /// #![feature(exit_status_error)]
1600 /// # #[cfg(unix)] {
1601 /// use std::process::Command;
1603 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1604 /// assert_eq!(bad.code(), Some(1));
1605 /// # } // #[cfg(unix)]
1608 pub fn code(&self) -> Option<i32> {
1609 self.code_nonzero().map(Into::into)
1612 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1614 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1616 /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1617 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1618 /// a type-level guarantee of nonzeroness.
1623 /// #![feature(exit_status_error)]
1624 /// # if cfg!(unix) {
1625 /// use std::num::NonZeroI32;
1626 /// use std::process::Command;
1628 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1629 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1630 /// # } // cfg!(unix)
1633 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1637 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1639 pub fn into_status(&self) -> ExitStatus {
1640 ExitStatus(self.0.into())
1644 #[unstable(feature = "exit_status_error", issue = "84908")]
1645 impl Into<ExitStatus> for ExitStatusError {
1646 fn into(self) -> ExitStatus {
1647 ExitStatus(self.0.into())
1651 #[unstable(feature = "exit_status_error", issue = "84908")]
1652 impl fmt::Display for ExitStatusError {
1653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1654 write!(f, "process exited unsuccessfully: {}", self.into_status())
1658 #[unstable(feature = "exit_status_error", issue = "84908")]
1659 impl crate::error::Error for ExitStatusError {}
1661 /// This type represents the status code the current process can return
1662 /// to its parent under normal termination.
1664 /// `ExitCode` is intended to be consumed only by the standard library (via
1665 /// [`Termination::report()`]), and intentionally does not provide accessors like
1666 /// `PartialEq`, `Eq`, or `Hash`. Instead the standard library provides the
1667 /// canonical `SUCCESS` and `FAILURE` exit codes as well as `From<u8> for
1668 /// ExitCode` for constructing other arbitrary exit codes.
1672 /// Numeric values used in this type don't have portable meanings, and
1673 /// different platforms may mask different amounts of them.
1675 /// For the platform's canonical successful and unsuccessful codes, see
1676 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1678 /// [`SUCCESS`]: ExitCode::SUCCESS
1679 /// [`FAILURE`]: ExitCode::FAILURE
1681 /// # Differences from `ExitStatus`
1683 /// `ExitCode` is intended for terminating the currently running process, via
1684 /// the `Termination` trait, in contrast to [`ExitStatus`], which represents the
1685 /// termination of a child process. These APIs are separate due to platform
1686 /// compatibility differences and their expected usage; it is not generally
1687 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1688 /// process after the fact.
1692 /// `ExitCode` can be returned from the `main` function of a crate, as it implements
1693 /// [`Termination`]:
1696 /// use std::process::ExitCode;
1697 /// # fn check_foo() -> bool { true }
1699 /// fn main() -> ExitCode {
1700 /// if !check_foo() {
1701 /// return ExitCode::from(42);
1704 /// ExitCode::SUCCESS
1707 #[derive(Clone, Copy, Debug)]
1708 #[stable(feature = "process_exitcode", since = "1.61.0")]
1709 pub struct ExitCode(imp::ExitCode);
1711 #[stable(feature = "process_exitcode", since = "1.61.0")]
1713 /// The canonical `ExitCode` for successful termination on this platform.
1715 /// Note that a `()`-returning `main` implicitly results in a successful
1716 /// termination, so there's no need to return this from `main` unless
1717 /// you're also returning other possible codes.
1718 #[stable(feature = "process_exitcode", since = "1.61.0")]
1719 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1721 /// The canonical `ExitCode` for unsuccessful termination on this platform.
1723 /// If you're only returning this and `SUCCESS` from `main`, consider
1724 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1725 /// return the same codes (but will also `eprintln!` the error).
1726 #[stable(feature = "process_exitcode", since = "1.61.0")]
1727 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1729 /// Exit the current process with the given `ExitCode`.
1731 /// Note that this has the same caveats as [`process::exit()`][exit], namely that this function
1732 /// terminates the process immediately, so no destructors on the current stack or any other
1733 /// thread's stack will be run. If a clean shutdown is needed, it is recommended to simply
1734 /// return this ExitCode from the `main` function, as demonstrated in the [type
1735 /// documentation](#examples).
1737 /// # Differences from `process::exit()`
1739 /// `process::exit()` accepts any `i32` value as the exit code for the process; however, there
1740 /// are platforms that only use a subset of that value (see [`process::exit` platform-specific
1741 /// behavior][exit#platform-specific-behavior]). `ExitCode` exists because of this; only
1742 /// `ExitCode`s that are supported by a majority of our platforms can be created, so those
1743 /// problems don't exist (as much) with this method.
1748 /// #![feature(exitcode_exit_method)]
1749 /// # use std::process::ExitCode;
1751 /// # enum UhOhError { GenericProblem, Specific, WithCode { exit_code: ExitCode, _x: () } }
1752 /// # impl fmt::Display for UhOhError {
1753 /// # fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() }
1755 /// // there's no way to gracefully recover from an UhOhError, so we just
1756 /// // print a message and exit
1757 /// fn handle_unrecoverable_error(err: UhOhError) -> ! {
1758 /// eprintln!("UH OH! {err}");
1759 /// let code = match err {
1760 /// UhOhError::GenericProblem => ExitCode::FAILURE,
1761 /// UhOhError::Specific => ExitCode::from(3),
1762 /// UhOhError::WithCode { exit_code, .. } => exit_code,
1764 /// code.exit_process()
1767 #[unstable(feature = "exitcode_exit_method", issue = "97100")]
1768 pub fn exit_process(self) -> ! {
1774 // This is private/perma-unstable because ExitCode is opaque; we don't know that i32 will serve
1775 // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
1776 // likely want to isolate users anything that could restrict the platform specific
1777 // representation of an ExitCode
1779 // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
1780 /// Convert an `ExitCode` into an i32
1782 feature = "process_exitcode_internals",
1783 reason = "exposed only for libstd",
1788 pub fn to_i32(self) -> i32 {
1793 #[stable(feature = "process_exitcode", since = "1.61.0")]
1794 impl From<u8> for ExitCode {
1795 /// Construct an `ExitCode` from an arbitrary u8 value.
1796 fn from(code: u8) -> Self {
1797 ExitCode(imp::ExitCode::from(code))
1802 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1803 /// error is returned.
1805 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1807 /// This is equivalent to sending a SIGKILL on Unix platforms.
1814 /// use std::process::Command;
1816 /// let mut command = Command::new("yes");
1817 /// if let Ok(mut child) = command.spawn() {
1818 /// child.kill().expect("command wasn't running");
1820 /// println!("yes command didn't start");
1824 /// [`ErrorKind`]: io::ErrorKind
1825 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1826 #[stable(feature = "process", since = "1.0.0")]
1827 pub fn kill(&mut self) -> io::Result<()> {
1831 /// Returns the OS-assigned process identifier associated with this child.
1838 /// use std::process::Command;
1840 /// let mut command = Command::new("ls");
1841 /// if let Ok(child) = command.spawn() {
1842 /// println!("Child's ID is {}", child.id());
1844 /// println!("ls command didn't start");
1848 #[stable(feature = "process_id", since = "1.3.0")]
1849 pub fn id(&self) -> u32 {
1853 /// Waits for the child to exit completely, returning the status that it
1854 /// exited with. This function will continue to have the same return value
1855 /// after it has been called at least once.
1857 /// The stdin handle to the child process, if any, will be closed
1858 /// before waiting. This helps avoid deadlock: it ensures that the
1859 /// child does not block waiting for input from the parent, while
1860 /// the parent waits for the child to exit.
1867 /// use std::process::Command;
1869 /// let mut command = Command::new("ls");
1870 /// if let Ok(mut child) = command.spawn() {
1871 /// child.wait().expect("command wasn't running");
1872 /// println!("Child has finished its execution!");
1874 /// println!("ls command didn't start");
1877 #[stable(feature = "process", since = "1.0.0")]
1878 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1879 drop(self.stdin.take());
1880 self.handle.wait().map(ExitStatus)
1883 /// Attempts to collect the exit status of the child if it has already
1886 /// This function will not block the calling thread and will only
1887 /// check to see if the child process has exited or not. If the child has
1888 /// exited then on Unix the process ID is reaped. This function is
1889 /// guaranteed to repeatedly return a successful exit status so long as the
1890 /// child has already exited.
1892 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1893 /// exit status is not available at this time then `Ok(None)` is returned.
1894 /// If an error occurs, then that error is returned.
1896 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1903 /// use std::process::Command;
1905 /// let mut child = Command::new("ls").spawn().unwrap();
1907 /// match child.try_wait() {
1908 /// Ok(Some(status)) => println!("exited with: {status}"),
1910 /// println!("status not ready yet, let's really wait");
1911 /// let res = child.wait();
1912 /// println!("result: {res:?}");
1914 /// Err(e) => println!("error attempting to wait: {e}"),
1917 #[stable(feature = "process_try_wait", since = "1.18.0")]
1918 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1919 Ok(self.handle.try_wait()?.map(ExitStatus))
1922 /// Simultaneously waits for the child to exit and collect all remaining
1923 /// output on the stdout/stderr handles, returning an `Output`
1926 /// The stdin handle to the child process, if any, will be closed
1927 /// before waiting. This helps avoid deadlock: it ensures that the
1928 /// child does not block waiting for input from the parent, while
1929 /// the parent waits for the child to exit.
1931 /// By default, stdin, stdout and stderr are inherited from the parent.
1932 /// In order to capture the output into this `Result<Output>` it is
1933 /// necessary to create new pipes between parent and child. Use
1934 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1939 /// use std::process::{Command, Stdio};
1941 /// let child = Command::new("/bin/cat")
1942 /// .arg("file.txt")
1943 /// .stdout(Stdio::piped())
1945 /// .expect("failed to execute child");
1947 /// let output = child
1948 /// .wait_with_output()
1949 /// .expect("failed to wait on child");
1951 /// assert!(output.status.success());
1954 #[stable(feature = "process", since = "1.0.0")]
1955 pub fn wait_with_output(mut self) -> io::Result<Output> {
1956 drop(self.stdin.take());
1958 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1959 match (self.stdout.take(), self.stderr.take()) {
1961 (Some(mut out), None) => {
1962 let res = out.read_to_end(&mut stdout);
1965 (None, Some(mut err)) => {
1966 let res = err.read_to_end(&mut stderr);
1969 (Some(out), Some(err)) => {
1970 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1975 let status = self.wait()?;
1976 Ok(Output { status, stdout, stderr })
1980 /// Terminates the current process with the specified exit code.
1982 /// This function will never return and will immediately terminate the current
1983 /// process. The exit code is passed through to the underlying OS and will be
1984 /// available for consumption by another process.
1986 /// Note that because this function never returns, and that it terminates the
1987 /// process, no destructors on the current stack or any other thread's stack
1988 /// will be run. If a clean shutdown is needed it is recommended to only call
1989 /// this function at a known point where there are no more destructors left
1990 /// to run; or, preferably, simply return a type implementing [`Termination`]
1991 /// (such as [`ExitCode`] or `Result`) from the `main` function and avoid this
1992 /// function altogether:
1995 /// # use std::io::Error as MyError;
1996 /// fn main() -> Result<(), MyError> {
2002 /// ## Platform-specific behavior
2004 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
2005 /// will be visible to a parent process inspecting the exit code. On most
2006 /// Unix-like platforms, only the eight least-significant bits are considered.
2008 /// For example, the exit code for this example will be `0` on Linux, but `256`
2012 /// use std::process;
2014 /// process::exit(0x0100);
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 pub fn exit(code: i32) -> ! {
2018 crate::rt::cleanup();
2019 crate::sys::os::exit(code)
2022 /// Terminates the process in an abnormal fashion.
2024 /// The function will never return and will immediately terminate the current
2025 /// process in a platform specific "abnormal" manner.
2027 /// Note that because this function never returns, and that it terminates the
2028 /// process, no destructors on the current stack or any other thread's stack
2031 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
2032 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
2034 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
2035 /// the current thread's stack and calls all destructors.
2036 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
2037 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
2038 /// [`panic!`] will still call the [panic hook] while `abort` will not.
2040 /// If a clean shutdown is needed it is recommended to only call
2041 /// this function at a known point where there are no more destructors left
2044 /// The process's termination will be similar to that from the C `abort()`
2045 /// function. On Unix, the process will terminate with signal `SIGABRT`, which
2046 /// typically means that the shell prints "Aborted".
2051 /// use std::process;
2054 /// println!("aborting");
2056 /// process::abort();
2058 /// // execution never gets here
2062 /// The `abort` function terminates the process, so the destructor will not
2063 /// get run on the example below:
2066 /// use std::process;
2070 /// impl Drop for HasDrop {
2071 /// fn drop(&mut self) {
2072 /// println!("This will never be printed!");
2077 /// let _x = HasDrop;
2078 /// process::abort();
2079 /// // the destructor implemented for HasDrop will never get run
2083 /// [panic hook]: crate::panic::set_hook
2084 #[stable(feature = "process_abort", since = "1.17.0")]
2086 pub fn abort() -> ! {
2087 crate::sys::abort_internal();
2090 /// Returns the OS-assigned process identifier associated with this process.
2097 /// use std::process;
2099 /// println!("My pid is {}", process::id());
2104 #[stable(feature = "getpid", since = "1.26.0")]
2105 pub fn id() -> u32 {
2106 crate::sys::os::getpid()
2109 /// A trait for implementing arbitrary return types in the `main` function.
2111 /// The C-main function only supports returning integers.
2112 /// So, every type implementing the `Termination` trait has to be converted
2115 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2116 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2118 /// Because different runtimes have different specifications on the return value
2119 /// of the `main` function, this trait is likely to be available only on
2120 /// standard library's runtime for convenience. Other runtimes are not required
2121 /// to provide similar functionality.
2122 #[cfg_attr(not(test), lang = "termination")]
2123 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2124 #[rustc_on_unimplemented(
2125 message = "`main` has invalid return type `{Self}`",
2126 label = "`main` can only return types that implement `{Termination}`"
2128 pub trait Termination {
2129 /// Is called to get the representation of the value as status code.
2130 /// This status code is returned to the operating system.
2131 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2132 fn report(self) -> ExitCode;
2135 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2136 impl Termination for () {
2138 fn report(self) -> ExitCode {
2143 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2144 impl<E: fmt::Debug> Termination for Result<(), E> {
2145 fn report(self) -> ExitCode {
2147 Ok(()) => ().report(),
2148 Err(err) => Err::<!, _>(err).report(),
2153 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2154 impl Termination for ! {
2155 fn report(self) -> ExitCode {
2160 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2161 impl<E: fmt::Debug> Termination for Result<!, E> {
2162 fn report(self) -> ExitCode {
2163 let Err(err) = self;
2164 // Ignore error if the write fails, for example because stderr is
2165 // already closed. There is not much point panicking at this point.
2166 let _ = writeln!(io::stderr(), "Error: {err:?}");
2171 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2172 impl<E: fmt::Debug> Termination for Result<Infallible, E> {
2173 fn report(self) -> ExitCode {
2174 let Err(err) = self;
2175 Err::<!, _>(err).report()
2179 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2180 impl Termination for ExitCode {
2182 fn report(self) -> ExitCode {