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
173 /// has been captured. You might find it helpful to do
175 /// ```compile_fail,E0425
176 /// let stdin = child.stdin.take().unwrap();
179 /// to avoid partially moving the `child` and thus blocking yourself from calling
180 /// functions on `child` while using `stdin`.
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()
366 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
367 self.inner.read_to_end(buf)
371 impl AsInner<AnonPipe> for ChildStdout {
372 fn as_inner(&self) -> &AnonPipe {
377 impl IntoInner<AnonPipe> for ChildStdout {
378 fn into_inner(self) -> AnonPipe {
383 impl FromInner<AnonPipe> for ChildStdout {
384 fn from_inner(pipe: AnonPipe) -> ChildStdout {
385 ChildStdout { inner: pipe }
389 #[stable(feature = "std_debug", since = "1.16.0")]
390 impl fmt::Debug for ChildStdout {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 f.debug_struct("ChildStdout").finish_non_exhaustive()
396 /// A handle to a child process's stderr.
398 /// This struct is used in the [`stderr`] field on [`Child`].
400 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
401 /// underlying file handle will be closed.
403 /// [`stderr`]: Child::stderr
405 #[stable(feature = "process", since = "1.0.0")]
406 pub struct ChildStderr {
410 // In addition to the `impl`s here, `ChildStderr` also has `impl`s for
411 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
412 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
413 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
414 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
416 #[stable(feature = "process", since = "1.0.0")]
417 impl Read for ChildStderr {
418 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
422 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
423 self.inner.read_vectored(bufs)
427 fn is_read_vectored(&self) -> bool {
428 self.inner.is_read_vectored()
432 impl AsInner<AnonPipe> for ChildStderr {
433 fn as_inner(&self) -> &AnonPipe {
438 impl IntoInner<AnonPipe> for ChildStderr {
439 fn into_inner(self) -> AnonPipe {
444 impl FromInner<AnonPipe> for ChildStderr {
445 fn from_inner(pipe: AnonPipe) -> ChildStderr {
446 ChildStderr { inner: pipe }
450 #[stable(feature = "std_debug", since = "1.16.0")]
451 impl fmt::Debug for ChildStderr {
452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453 f.debug_struct("ChildStderr").finish_non_exhaustive()
457 /// A process builder, providing fine-grained control
458 /// over how a new process should be spawned.
460 /// A default configuration can be
461 /// generated using `Command::new(program)`, where `program` gives a path to the
462 /// program to be executed. Additional builder methods allow the configuration
463 /// to be changed (for example, by adding arguments) prior to spawning:
466 /// use std::process::Command;
468 /// let output = if cfg!(target_os = "windows") {
469 /// Command::new("cmd")
470 /// .args(["/C", "echo hello"])
472 /// .expect("failed to execute process")
474 /// Command::new("sh")
476 /// .arg("echo hello")
478 /// .expect("failed to execute process")
481 /// let hello = output.stdout;
484 /// `Command` can be reused to spawn multiple processes. The builder methods
485 /// change the command without needing to immediately spawn the process.
488 /// use std::process::Command;
490 /// let mut echo_hello = Command::new("sh");
491 /// echo_hello.arg("-c")
492 /// .arg("echo hello");
493 /// let hello_1 = echo_hello.output().expect("failed to execute process");
494 /// let hello_2 = echo_hello.output().expect("failed to execute process");
497 /// Similarly, you can call builder methods after spawning a process and then
498 /// spawn a new process with the modified settings.
501 /// use std::process::Command;
503 /// let mut list_dir = Command::new("ls");
505 /// // Execute `ls` in the current directory of the program.
506 /// list_dir.status().expect("process failed to execute");
510 /// // Change `ls` to execute in the root directory.
511 /// list_dir.current_dir("/");
513 /// // And then execute `ls` again but in the root directory.
514 /// list_dir.status().expect("process failed to execute");
516 #[stable(feature = "process", since = "1.0.0")]
521 /// Allows extension traits within `std`.
522 #[unstable(feature = "sealed", issue = "none")]
523 impl crate::sealed::Sealed for Command {}
526 /// Constructs a new `Command` for launching the program at
527 /// path `program`, with the following default configuration:
529 /// * No arguments to the program
530 /// * Inherit the current process's environment
531 /// * Inherit the current process's working directory
532 /// * Inherit stdin/stdout/stderr for [`spawn`] or [`status`], but create pipes for [`output`]
534 /// [`spawn`]: Self::spawn
535 /// [`status`]: Self::status
536 /// [`output`]: Self::output
538 /// Builder methods are provided to change these defaults and
539 /// otherwise configure the process.
541 /// If `program` is not an absolute path, the `PATH` will be searched in
542 /// an OS-defined way.
544 /// The search path to be used may be controlled by setting the
545 /// `PATH` environment variable on the Command,
546 /// but this has some implementation limitations on Windows
547 /// (see issue #37519).
554 /// use std::process::Command;
556 /// Command::new("sh")
558 /// .expect("sh command failed to start");
560 #[stable(feature = "process", since = "1.0.0")]
561 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
562 Command { inner: imp::Command::new(program.as_ref()) }
565 /// Adds an argument to pass to the program.
567 /// Only one argument can be passed per use. So instead of:
570 /// # std::process::Command::new("sh")
571 /// .arg("-C /path/to/repo")
578 /// # std::process::Command::new("sh")
580 /// .arg("/path/to/repo")
584 /// To pass multiple arguments see [`args`].
586 /// [`args`]: Command::args
588 /// Note that the argument is not passed through a shell, but given
589 /// literally to the program. This means that shell syntax like quotes,
590 /// escaped characters, word splitting, glob patterns, substitution, etc.
598 /// use std::process::Command;
600 /// Command::new("ls")
604 /// .expect("ls command failed to start");
606 #[stable(feature = "process", since = "1.0.0")]
607 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
608 self.inner.arg(arg.as_ref());
612 /// Adds multiple arguments to pass to the program.
614 /// To pass a single argument see [`arg`].
616 /// [`arg`]: Command::arg
618 /// Note that the arguments are not passed through a shell, but given
619 /// literally to the program. This means that shell syntax like quotes,
620 /// escaped characters, word splitting, glob patterns, substitution, etc.
628 /// use std::process::Command;
630 /// Command::new("ls")
631 /// .args(["-l", "-a"])
633 /// .expect("ls command failed to start");
635 #[stable(feature = "process", since = "1.0.0")]
636 pub fn args<I, S>(&mut self, args: I) -> &mut Command
638 I: IntoIterator<Item = S>,
642 self.arg(arg.as_ref());
647 /// Inserts or updates an environment variable mapping.
649 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
650 /// and case-sensitive on all other platforms.
657 /// use std::process::Command;
659 /// Command::new("ls")
660 /// .env("PATH", "/bin")
662 /// .expect("ls command failed to start");
664 #[stable(feature = "process", since = "1.0.0")]
665 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
670 self.inner.env_mut().set(key.as_ref(), val.as_ref());
674 /// Adds or updates multiple environment variable mappings.
681 /// use std::process::{Command, Stdio};
683 /// use std::collections::HashMap;
685 /// let filtered_env : HashMap<String, String> =
686 /// env::vars().filter(|&(ref k, _)|
687 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
690 /// Command::new("printenv")
691 /// .stdin(Stdio::null())
692 /// .stdout(Stdio::inherit())
694 /// .envs(&filtered_env)
696 /// .expect("printenv failed to start");
698 #[stable(feature = "command_envs", since = "1.19.0")]
699 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
701 I: IntoIterator<Item = (K, V)>,
705 for (ref key, ref val) in vars {
706 self.inner.env_mut().set(key.as_ref(), val.as_ref());
711 /// Removes an environment variable mapping.
718 /// use std::process::Command;
720 /// Command::new("ls")
721 /// .env_remove("PATH")
723 /// .expect("ls command failed to start");
725 #[stable(feature = "process", since = "1.0.0")]
726 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
727 self.inner.env_mut().remove(key.as_ref());
731 /// Clears the entire environment map for the child process.
738 /// use std::process::Command;
740 /// Command::new("ls")
743 /// .expect("ls command failed to start");
745 #[stable(feature = "process", since = "1.0.0")]
746 pub fn env_clear(&mut self) -> &mut Command {
747 self.inner.env_mut().clear();
751 /// Sets the working directory for the child process.
753 /// # Platform-specific behavior
755 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
756 /// whether it should be interpreted relative to the parent's working
757 /// directory or relative to `current_dir`. The behavior in this case is
758 /// platform specific and unstable, and it's recommended to use
759 /// [`canonicalize`] to get an absolute program path instead.
766 /// use std::process::Command;
768 /// Command::new("ls")
769 /// .current_dir("/bin")
771 /// .expect("ls command failed to start");
774 /// [`canonicalize`]: crate::fs::canonicalize
775 #[stable(feature = "process", since = "1.0.0")]
776 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
777 self.inner.cwd(dir.as_ref().as_ref());
781 /// Configuration for the child process's standard input (stdin) handle.
783 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
784 /// defaults to [`piped`] when used with [`output`].
786 /// [`inherit`]: Stdio::inherit
787 /// [`piped`]: Stdio::piped
788 /// [`spawn`]: Self::spawn
789 /// [`status`]: Self::status
790 /// [`output`]: Self::output
797 /// use std::process::{Command, Stdio};
799 /// Command::new("ls")
800 /// .stdin(Stdio::null())
802 /// .expect("ls command failed to start");
804 #[stable(feature = "process", since = "1.0.0")]
805 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
806 self.inner.stdin(cfg.into().0);
810 /// Configuration for the child process's standard output (stdout) handle.
812 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
813 /// defaults to [`piped`] when used with [`output`].
815 /// [`inherit`]: Stdio::inherit
816 /// [`piped`]: Stdio::piped
817 /// [`spawn`]: Self::spawn
818 /// [`status`]: Self::status
819 /// [`output`]: Self::output
826 /// use std::process::{Command, Stdio};
828 /// Command::new("ls")
829 /// .stdout(Stdio::null())
831 /// .expect("ls command failed to start");
833 #[stable(feature = "process", since = "1.0.0")]
834 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
835 self.inner.stdout(cfg.into().0);
839 /// Configuration for the child process's standard error (stderr) handle.
841 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
842 /// defaults to [`piped`] when used with [`output`].
844 /// [`inherit`]: Stdio::inherit
845 /// [`piped`]: Stdio::piped
846 /// [`spawn`]: Self::spawn
847 /// [`status`]: Self::status
848 /// [`output`]: Self::output
855 /// use std::process::{Command, Stdio};
857 /// Command::new("ls")
858 /// .stderr(Stdio::null())
860 /// .expect("ls command failed to start");
862 #[stable(feature = "process", since = "1.0.0")]
863 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
864 self.inner.stderr(cfg.into().0);
868 /// Executes the command as a child process, returning a handle to it.
870 /// By default, stdin, stdout and stderr are inherited from the parent.
877 /// use std::process::Command;
879 /// Command::new("ls")
881 /// .expect("ls command failed to start");
883 #[stable(feature = "process", since = "1.0.0")]
884 pub fn spawn(&mut self) -> io::Result<Child> {
885 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
888 /// Executes the command as a child process, waiting for it to finish and
889 /// collecting all of its output.
891 /// By default, stdout and stderr are captured (and used to provide the
892 /// resulting output). Stdin is not inherited from the parent and any
893 /// attempt by the child process to read from the stdin stream will result
894 /// in the stream immediately closing.
899 /// use std::process::Command;
900 /// use std::io::{self, Write};
901 /// let output = Command::new("/bin/cat")
904 /// .expect("failed to execute process");
906 /// println!("status: {}", output.status);
907 /// io::stdout().write_all(&output.stdout).unwrap();
908 /// io::stderr().write_all(&output.stderr).unwrap();
910 /// assert!(output.status.success());
912 #[stable(feature = "process", since = "1.0.0")]
913 pub fn output(&mut self) -> io::Result<Output> {
914 let (status, stdout, stderr) = self.inner.output()?;
915 Ok(Output { status: ExitStatus(status), stdout, stderr })
918 /// Executes a command as a child process, waiting for it to finish and
919 /// collecting its status.
921 /// By default, stdin, stdout and stderr are inherited from the parent.
926 /// use std::process::Command;
928 /// let status = Command::new("/bin/cat")
931 /// .expect("failed to execute process");
933 /// println!("process finished with: {status}");
935 /// assert!(status.success());
937 #[stable(feature = "process", since = "1.0.0")]
938 pub fn status(&mut self) -> io::Result<ExitStatus> {
940 .spawn(imp::Stdio::Inherit, true)
941 .map(Child::from_inner)
942 .and_then(|mut p| p.wait())
945 /// Returns the path to the program that was given to [`Command::new`].
950 /// use std::process::Command;
952 /// let cmd = Command::new("echo");
953 /// assert_eq!(cmd.get_program(), "echo");
956 #[stable(feature = "command_access", since = "1.57.0")]
957 pub fn get_program(&self) -> &OsStr {
958 self.inner.get_program()
961 /// Returns an iterator of the arguments that will be passed to the program.
963 /// This does not include the path to the program as the first argument;
964 /// it only includes the arguments specified with [`Command::arg`] and
965 /// [`Command::args`].
970 /// use std::ffi::OsStr;
971 /// use std::process::Command;
973 /// let mut cmd = Command::new("echo");
974 /// cmd.arg("first").arg("second");
975 /// let args: Vec<&OsStr> = cmd.get_args().collect();
976 /// assert_eq!(args, &["first", "second"]);
978 #[stable(feature = "command_access", since = "1.57.0")]
979 pub fn get_args(&self) -> CommandArgs<'_> {
980 CommandArgs { inner: self.inner.get_args() }
983 /// Returns an iterator of the environment variables that will be set when
984 /// the process is spawned.
986 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
987 /// value is the key, and the second is the value, which is [`None`] if
988 /// the environment variable is to be explicitly removed.
990 /// This only includes environment variables explicitly set with
991 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
992 /// does not include environment variables that will be inherited by the
998 /// use std::ffi::OsStr;
999 /// use std::process::Command;
1001 /// let mut cmd = Command::new("ls");
1002 /// cmd.env("TERM", "dumb").env_remove("TZ");
1003 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1004 /// assert_eq!(envs, &[
1005 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1006 /// (OsStr::new("TZ"), None)
1009 #[stable(feature = "command_access", since = "1.57.0")]
1010 pub fn get_envs(&self) -> CommandEnvs<'_> {
1011 self.inner.get_envs()
1014 /// Returns the working directory for the child process.
1016 /// This returns [`None`] if the working directory will not be changed.
1021 /// use std::path::Path;
1022 /// use std::process::Command;
1024 /// let mut cmd = Command::new("ls");
1025 /// assert_eq!(cmd.get_current_dir(), None);
1026 /// cmd.current_dir("/bin");
1027 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1030 #[stable(feature = "command_access", since = "1.57.0")]
1031 pub fn get_current_dir(&self) -> Option<&Path> {
1032 self.inner.get_current_dir()
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 impl fmt::Debug for Command {
1038 /// Format the program and arguments of a Command for display. Any
1039 /// non-utf8 data is lossily converted using the utf8 replacement
1042 /// The default format approximates a shell invocation of the program along with its
1043 /// arguments. It does not include most of the other command properties. The output is not guaranteed to work
1044 /// (e.g. due to lack of shell-escaping or differences in path resolution)
1045 /// On some platforms you can use [the alternate syntax] to show more fields.
1047 /// Note that the debug implementation is platform-specific.
1049 /// [the alternate syntax]: fmt#sign0
1050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1055 impl AsInner<imp::Command> for Command {
1056 fn as_inner(&self) -> &imp::Command {
1061 impl AsInnerMut<imp::Command> for Command {
1062 fn as_inner_mut(&mut self) -> &mut imp::Command {
1067 /// An iterator over the command arguments.
1069 /// This struct is created by [`Command::get_args`]. See its documentation for
1071 #[must_use = "iterators are lazy and do nothing unless consumed"]
1072 #[stable(feature = "command_access", since = "1.57.0")]
1074 pub struct CommandArgs<'a> {
1075 inner: imp::CommandArgs<'a>,
1078 #[stable(feature = "command_access", since = "1.57.0")]
1079 impl<'a> Iterator for CommandArgs<'a> {
1080 type Item = &'a OsStr;
1081 fn next(&mut self) -> Option<&'a OsStr> {
1084 fn size_hint(&self) -> (usize, Option<usize>) {
1085 self.inner.size_hint()
1089 #[stable(feature = "command_access", since = "1.57.0")]
1090 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1091 fn len(&self) -> usize {
1094 fn is_empty(&self) -> bool {
1095 self.inner.is_empty()
1099 /// The output of a finished process.
1101 /// This is returned in a Result by either the [`output`] method of a
1102 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1105 /// [`output`]: Command::output
1106 /// [`wait_with_output`]: Child::wait_with_output
1107 #[derive(PartialEq, Eq, Clone)]
1108 #[stable(feature = "process", since = "1.0.0")]
1110 /// The status (exit code) of the process.
1111 #[stable(feature = "process", since = "1.0.0")]
1112 pub status: ExitStatus,
1113 /// The data that the process wrote to stdout.
1114 #[stable(feature = "process", since = "1.0.0")]
1115 pub stdout: Vec<u8>,
1116 /// The data that the process wrote to stderr.
1117 #[stable(feature = "process", since = "1.0.0")]
1118 pub stderr: Vec<u8>,
1121 // If either stderr or stdout are valid utf8 strings it prints the valid
1122 // strings, otherwise it prints the byte sequence instead
1123 #[stable(feature = "process_output_debug", since = "1.7.0")]
1124 impl fmt::Debug for Output {
1125 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 let stdout_utf8 = str::from_utf8(&self.stdout);
1127 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1129 Err(_) => &self.stdout,
1132 let stderr_utf8 = str::from_utf8(&self.stderr);
1133 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1135 Err(_) => &self.stderr,
1138 fmt.debug_struct("Output")
1139 .field("status", &self.status)
1140 .field("stdout", stdout_debug)
1141 .field("stderr", stderr_debug)
1146 /// Describes what to do with a standard I/O stream for a child process when
1147 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1149 /// [`stdin`]: Command::stdin
1150 /// [`stdout`]: Command::stdout
1151 /// [`stderr`]: Command::stderr
1152 #[stable(feature = "process", since = "1.0.0")]
1153 pub struct Stdio(imp::Stdio);
1156 /// A new pipe should be arranged to connect the parent and child processes.
1163 /// use std::process::{Command, Stdio};
1165 /// let output = Command::new("echo")
1166 /// .arg("Hello, world!")
1167 /// .stdout(Stdio::piped())
1169 /// .expect("Failed to execute command");
1171 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1172 /// // Nothing echoed to console
1178 /// use std::io::Write;
1179 /// use std::process::{Command, Stdio};
1181 /// let mut child = Command::new("rev")
1182 /// .stdin(Stdio::piped())
1183 /// .stdout(Stdio::piped())
1185 /// .expect("Failed to spawn child process");
1187 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1188 /// std::thread::spawn(move || {
1189 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1192 /// let output = child.wait_with_output().expect("Failed to read stdout");
1193 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1196 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1197 /// stdout and stderr at the same time may cause a deadlock.
1198 /// This is an issue when running any program that doesn't guarantee that it reads
1199 /// its entire stdin before writing more than a pipe buffer's worth of output.
1200 /// The size of a pipe buffer varies on different targets.
1203 #[stable(feature = "process", since = "1.0.0")]
1204 pub fn piped() -> Stdio {
1205 Stdio(imp::Stdio::MakePipe)
1208 /// The child inherits from the corresponding parent descriptor.
1215 /// use std::process::{Command, Stdio};
1217 /// let output = Command::new("echo")
1218 /// .arg("Hello, world!")
1219 /// .stdout(Stdio::inherit())
1221 /// .expect("Failed to execute command");
1223 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1224 /// // "Hello, world!" echoed to console
1230 /// use std::process::{Command, Stdio};
1231 /// use std::io::{self, Write};
1233 /// let output = Command::new("rev")
1234 /// .stdin(Stdio::inherit())
1235 /// .stdout(Stdio::piped())
1237 /// .expect("Failed to execute command");
1239 /// print!("You piped in the reverse of: ");
1240 /// io::stdout().write_all(&output.stdout).unwrap();
1243 #[stable(feature = "process", since = "1.0.0")]
1244 pub fn inherit() -> Stdio {
1245 Stdio(imp::Stdio::Inherit)
1248 /// This stream will be ignored. This is the equivalent of attaching the
1249 /// stream to `/dev/null`.
1256 /// use std::process::{Command, Stdio};
1258 /// let output = Command::new("echo")
1259 /// .arg("Hello, world!")
1260 /// .stdout(Stdio::null())
1262 /// .expect("Failed to execute command");
1264 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1265 /// // Nothing echoed to console
1271 /// use std::process::{Command, Stdio};
1273 /// let output = Command::new("rev")
1274 /// .stdin(Stdio::null())
1275 /// .stdout(Stdio::piped())
1277 /// .expect("Failed to execute command");
1279 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1280 /// // Ignores any piped-in input
1283 #[stable(feature = "process", since = "1.0.0")]
1284 pub fn null() -> Stdio {
1285 Stdio(imp::Stdio::Null)
1288 /// Returns `true` if this requires [`Command`] to create a new pipe.
1293 /// #![feature(stdio_makes_pipe)]
1294 /// use std::process::Stdio;
1296 /// let io = Stdio::piped();
1297 /// assert_eq!(io.makes_pipe(), true);
1299 #[unstable(feature = "stdio_makes_pipe", issue = "98288")]
1300 pub fn makes_pipe(&self) -> bool {
1301 matches!(self.0, imp::Stdio::MakePipe)
1305 impl FromInner<imp::Stdio> for Stdio {
1306 fn from_inner(inner: imp::Stdio) -> Stdio {
1311 #[stable(feature = "std_debug", since = "1.16.0")]
1312 impl fmt::Debug for Stdio {
1313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1314 f.debug_struct("Stdio").finish_non_exhaustive()
1318 #[stable(feature = "stdio_from", since = "1.20.0")]
1319 impl From<ChildStdin> for Stdio {
1320 /// Converts a [`ChildStdin`] into a [`Stdio`].
1324 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1327 /// use std::process::{Command, Stdio};
1329 /// let reverse = Command::new("rev")
1330 /// .stdin(Stdio::piped())
1332 /// .expect("failed reverse command");
1334 /// let _echo = Command::new("echo")
1335 /// .arg("Hello, world!")
1336 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1338 /// .expect("failed echo command");
1340 /// // "!dlrow ,olleH" echoed to console
1342 fn from(child: ChildStdin) -> Stdio {
1343 Stdio::from_inner(child.into_inner().into())
1347 #[stable(feature = "stdio_from", since = "1.20.0")]
1348 impl From<ChildStdout> for Stdio {
1349 /// Converts a [`ChildStdout`] into a [`Stdio`].
1353 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1356 /// use std::process::{Command, Stdio};
1358 /// let hello = Command::new("echo")
1359 /// .arg("Hello, world!")
1360 /// .stdout(Stdio::piped())
1362 /// .expect("failed echo command");
1364 /// let reverse = Command::new("rev")
1365 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1367 /// .expect("failed reverse command");
1369 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1371 fn from(child: ChildStdout) -> Stdio {
1372 Stdio::from_inner(child.into_inner().into())
1376 #[stable(feature = "stdio_from", since = "1.20.0")]
1377 impl From<ChildStderr> for Stdio {
1378 /// Converts a [`ChildStderr`] into a [`Stdio`].
1383 /// use std::process::{Command, Stdio};
1385 /// let reverse = Command::new("rev")
1386 /// .arg("non_existing_file.txt")
1387 /// .stderr(Stdio::piped())
1389 /// .expect("failed reverse command");
1391 /// let cat = Command::new("cat")
1393 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1395 /// .expect("failed echo command");
1398 /// String::from_utf8_lossy(&cat.stdout),
1399 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1402 fn from(child: ChildStderr) -> Stdio {
1403 Stdio::from_inner(child.into_inner().into())
1407 #[stable(feature = "stdio_from", since = "1.20.0")]
1408 impl From<fs::File> for Stdio {
1409 /// Converts a [`File`](fs::File) into a [`Stdio`].
1413 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1416 /// use std::fs::File;
1417 /// use std::process::Command;
1419 /// // With the `foo.txt` file containing `Hello, world!"
1420 /// let file = File::open("foo.txt").unwrap();
1422 /// let reverse = Command::new("rev")
1423 /// .stdin(file) // Implicit File conversion into a Stdio
1425 /// .expect("failed reverse command");
1427 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1429 fn from(file: fs::File) -> Stdio {
1430 Stdio::from_inner(file.into_inner().into())
1434 /// Describes the result of a process after it has terminated.
1436 /// This `struct` is used to represent the exit status or other termination of a child process.
1437 /// Child processes are created via the [`Command`] struct and their exit
1438 /// status is exposed through the [`status`] method, or the [`wait`] method
1439 /// of a [`Child`] process.
1441 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1442 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1444 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1445 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1447 /// # Differences from `ExitCode`
1449 /// [`ExitCode`] is intended for terminating the currently running process, via
1450 /// the `Termination` trait, in contrast to `ExitStatus`, which represents the
1451 /// termination of a child process. These APIs are separate due to platform
1452 /// compatibility differences and their expected usage; it is not generally
1453 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1454 /// process after the fact.
1456 /// [`status`]: Command::status
1457 /// [`wait`]: Child::wait
1459 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1460 // vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1461 // matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1462 // mean an underlying system call such as `_exit`.
1463 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1464 #[stable(feature = "process", since = "1.0.0")]
1465 pub struct ExitStatus(imp::ExitStatus);
1467 /// Allows extension traits within `std`.
1468 #[unstable(feature = "sealed", issue = "none")]
1469 impl crate::sealed::Sealed for ExitStatus {}
1472 /// Was termination successful? Returns a `Result`.
1477 /// #![feature(exit_status_error)]
1478 /// # if cfg!(unix) {
1479 /// use std::process::Command;
1481 /// let status = Command::new("ls")
1482 /// .arg("/dev/nonexistent")
1484 /// .expect("ls could not be executed");
1486 /// println!("ls: {status}");
1487 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1488 /// # } // cfg!(unix)
1490 #[unstable(feature = "exit_status_error", issue = "84908")]
1491 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1492 self.0.exit_ok().map_err(ExitStatusError)
1495 /// Was termination successful? Signal termination is not considered a
1496 /// success, and success is defined as a zero exit status.
1501 /// use std::process::Command;
1503 /// let status = Command::new("mkdir")
1504 /// .arg("projects")
1506 /// .expect("failed to execute mkdir");
1508 /// if status.success() {
1509 /// println!("'projects/' directory created");
1511 /// println!("failed to create 'projects/' directory: {status}");
1515 #[stable(feature = "process", since = "1.0.0")]
1516 pub fn success(&self) -> bool {
1517 self.0.exit_ok().is_ok()
1520 /// Returns the exit code of the process, if any.
1522 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1523 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1524 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1525 /// runtime system (often, for example, 255, 254, 127 or 126).
1527 /// On Unix, this will return `None` if the process was terminated by a signal.
1528 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1529 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1534 /// use std::process::Command;
1536 /// let status = Command::new("mkdir")
1537 /// .arg("projects")
1539 /// .expect("failed to execute mkdir");
1541 /// match status.code() {
1542 /// Some(code) => println!("Exited with status code: {code}"),
1543 /// None => println!("Process terminated by signal")
1547 #[stable(feature = "process", since = "1.0.0")]
1548 pub fn code(&self) -> Option<i32> {
1553 impl AsInner<imp::ExitStatus> for ExitStatus {
1554 fn as_inner(&self) -> &imp::ExitStatus {
1559 impl FromInner<imp::ExitStatus> for ExitStatus {
1560 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1565 #[stable(feature = "process", since = "1.0.0")]
1566 impl fmt::Display for ExitStatus {
1567 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1572 /// Allows extension traits within `std`.
1573 #[unstable(feature = "sealed", issue = "none")]
1574 impl crate::sealed::Sealed for ExitStatusError {}
1576 /// Describes the result of a process after it has failed
1578 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1583 /// #![feature(exit_status_error)]
1584 /// # if cfg!(unix) {
1585 /// use std::process::{Command, ExitStatusError};
1587 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1588 /// Command::new(cmd).status().unwrap().exit_ok()?;
1592 /// run("true").unwrap();
1593 /// run("false").unwrap_err();
1594 /// # } // cfg!(unix)
1596 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1597 #[unstable(feature = "exit_status_error", issue = "84908")]
1598 // The definition of imp::ExitStatusError should ideally be such that
1599 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1600 pub struct ExitStatusError(imp::ExitStatusError);
1602 #[unstable(feature = "exit_status_error", issue = "84908")]
1603 impl ExitStatusError {
1604 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1606 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1607 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1608 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1609 /// runtime system (often, for example, 255, 254, 127 or 126).
1611 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1612 /// handle such situations specially, consider using methods from
1613 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1615 /// If the process finished by calling `exit` with a nonzero value, this will return
1616 /// that exit status.
1618 /// If the error was something else, it will return `None`.
1620 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1621 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1626 /// #![feature(exit_status_error)]
1627 /// # #[cfg(unix)] {
1628 /// use std::process::Command;
1630 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1631 /// assert_eq!(bad.code(), Some(1));
1632 /// # } // #[cfg(unix)]
1635 pub fn code(&self) -> Option<i32> {
1636 self.code_nonzero().map(Into::into)
1639 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1641 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1643 /// Plain `code`, returning a plain integer, is provided because it is often more convenient.
1644 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1645 /// a type-level guarantee of nonzeroness.
1650 /// #![feature(exit_status_error)]
1651 /// # if cfg!(unix) {
1652 /// use std::num::NonZeroI32;
1653 /// use std::process::Command;
1655 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1656 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1657 /// # } // cfg!(unix)
1660 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1664 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1666 pub fn into_status(&self) -> ExitStatus {
1667 ExitStatus(self.0.into())
1671 #[unstable(feature = "exit_status_error", issue = "84908")]
1672 impl Into<ExitStatus> for ExitStatusError {
1673 fn into(self) -> ExitStatus {
1674 ExitStatus(self.0.into())
1678 #[unstable(feature = "exit_status_error", issue = "84908")]
1679 impl fmt::Display for ExitStatusError {
1680 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1681 write!(f, "process exited unsuccessfully: {}", self.into_status())
1685 #[unstable(feature = "exit_status_error", issue = "84908")]
1686 impl crate::error::Error for ExitStatusError {}
1688 /// This type represents the status code the current process can return
1689 /// to its parent under normal termination.
1691 /// `ExitCode` is intended to be consumed only by the standard library (via
1692 /// [`Termination::report()`]), and intentionally does not provide accessors like
1693 /// `PartialEq`, `Eq`, or `Hash`. Instead the standard library provides the
1694 /// canonical `SUCCESS` and `FAILURE` exit codes as well as `From<u8> for
1695 /// ExitCode` for constructing other arbitrary exit codes.
1699 /// Numeric values used in this type don't have portable meanings, and
1700 /// different platforms may mask different amounts of them.
1702 /// For the platform's canonical successful and unsuccessful codes, see
1703 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1705 /// [`SUCCESS`]: ExitCode::SUCCESS
1706 /// [`FAILURE`]: ExitCode::FAILURE
1708 /// # Differences from `ExitStatus`
1710 /// `ExitCode` is intended for terminating the currently running process, via
1711 /// the `Termination` trait, in contrast to [`ExitStatus`], which represents the
1712 /// termination of a child process. These APIs are separate due to platform
1713 /// compatibility differences and their expected usage; it is not generally
1714 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1715 /// process after the fact.
1719 /// `ExitCode` can be returned from the `main` function of a crate, as it implements
1720 /// [`Termination`]:
1723 /// use std::process::ExitCode;
1724 /// # fn check_foo() -> bool { true }
1726 /// fn main() -> ExitCode {
1727 /// if !check_foo() {
1728 /// return ExitCode::from(42);
1731 /// ExitCode::SUCCESS
1734 #[derive(Clone, Copy, Debug)]
1735 #[stable(feature = "process_exitcode", since = "1.61.0")]
1736 pub struct ExitCode(imp::ExitCode);
1738 /// Allows extension traits within `std`.
1739 #[unstable(feature = "sealed", issue = "none")]
1740 impl crate::sealed::Sealed for ExitCode {}
1742 #[stable(feature = "process_exitcode", since = "1.61.0")]
1744 /// The canonical `ExitCode` for successful termination on this platform.
1746 /// Note that a `()`-returning `main` implicitly results in a successful
1747 /// termination, so there's no need to return this from `main` unless
1748 /// you're also returning other possible codes.
1749 #[stable(feature = "process_exitcode", since = "1.61.0")]
1750 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1752 /// The canonical `ExitCode` for unsuccessful termination on this platform.
1754 /// If you're only returning this and `SUCCESS` from `main`, consider
1755 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1756 /// return the same codes (but will also `eprintln!` the error).
1757 #[stable(feature = "process_exitcode", since = "1.61.0")]
1758 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1760 /// Exit the current process with the given `ExitCode`.
1762 /// Note that this has the same caveats as [`process::exit()`][exit], namely that this function
1763 /// terminates the process immediately, so no destructors on the current stack or any other
1764 /// thread's stack will be run. If a clean shutdown is needed, it is recommended to simply
1765 /// return this ExitCode from the `main` function, as demonstrated in the [type
1766 /// documentation](#examples).
1768 /// # Differences from `process::exit()`
1770 /// `process::exit()` accepts any `i32` value as the exit code for the process; however, there
1771 /// are platforms that only use a subset of that value (see [`process::exit` platform-specific
1772 /// behavior][exit#platform-specific-behavior]). `ExitCode` exists because of this; only
1773 /// `ExitCode`s that are supported by a majority of our platforms can be created, so those
1774 /// problems don't exist (as much) with this method.
1779 /// #![feature(exitcode_exit_method)]
1780 /// # use std::process::ExitCode;
1782 /// # enum UhOhError { GenericProblem, Specific, WithCode { exit_code: ExitCode, _x: () } }
1783 /// # impl fmt::Display for UhOhError {
1784 /// # fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() }
1786 /// // there's no way to gracefully recover from an UhOhError, so we just
1787 /// // print a message and exit
1788 /// fn handle_unrecoverable_error(err: UhOhError) -> ! {
1789 /// eprintln!("UH OH! {err}");
1790 /// let code = match err {
1791 /// UhOhError::GenericProblem => ExitCode::FAILURE,
1792 /// UhOhError::Specific => ExitCode::from(3),
1793 /// UhOhError::WithCode { exit_code, .. } => exit_code,
1795 /// code.exit_process()
1798 #[unstable(feature = "exitcode_exit_method", issue = "97100")]
1799 pub fn exit_process(self) -> ! {
1805 // This is private/perma-unstable because ExitCode is opaque; we don't know that i32 will serve
1806 // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
1807 // likely want to isolate users anything that could restrict the platform specific
1808 // representation of an ExitCode
1810 // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
1811 /// Convert an `ExitCode` into an i32
1813 feature = "process_exitcode_internals",
1814 reason = "exposed only for libstd",
1819 pub fn to_i32(self) -> i32 {
1824 #[stable(feature = "process_exitcode", since = "1.61.0")]
1825 impl From<u8> for ExitCode {
1826 /// Construct an `ExitCode` from an arbitrary u8 value.
1827 fn from(code: u8) -> Self {
1828 ExitCode(imp::ExitCode::from(code))
1832 impl AsInner<imp::ExitCode> for ExitCode {
1833 fn as_inner(&self) -> &imp::ExitCode {
1838 impl FromInner<imp::ExitCode> for ExitCode {
1839 fn from_inner(s: imp::ExitCode) -> ExitCode {
1845 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1846 /// error is returned.
1848 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1850 /// This is equivalent to sending a SIGKILL on Unix platforms.
1857 /// use std::process::Command;
1859 /// let mut command = Command::new("yes");
1860 /// if let Ok(mut child) = command.spawn() {
1861 /// child.kill().expect("command wasn't running");
1863 /// println!("yes command didn't start");
1867 /// [`ErrorKind`]: io::ErrorKind
1868 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1869 #[stable(feature = "process", since = "1.0.0")]
1870 pub fn kill(&mut self) -> io::Result<()> {
1874 /// Returns the OS-assigned process identifier associated with this child.
1881 /// use std::process::Command;
1883 /// let mut command = Command::new("ls");
1884 /// if let Ok(child) = command.spawn() {
1885 /// println!("Child's ID is {}", child.id());
1887 /// println!("ls command didn't start");
1891 #[stable(feature = "process_id", since = "1.3.0")]
1892 pub fn id(&self) -> u32 {
1896 /// Waits for the child to exit completely, returning the status that it
1897 /// exited with. This function will continue to have the same return value
1898 /// after it has been called at least once.
1900 /// The stdin handle to the child process, if any, will be closed
1901 /// before waiting. This helps avoid deadlock: it ensures that the
1902 /// child does not block waiting for input from the parent, while
1903 /// the parent waits for the child to exit.
1910 /// use std::process::Command;
1912 /// let mut command = Command::new("ls");
1913 /// if let Ok(mut child) = command.spawn() {
1914 /// child.wait().expect("command wasn't running");
1915 /// println!("Child has finished its execution!");
1917 /// println!("ls command didn't start");
1920 #[stable(feature = "process", since = "1.0.0")]
1921 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1922 drop(self.stdin.take());
1923 self.handle.wait().map(ExitStatus)
1926 /// Attempts to collect the exit status of the child if it has already
1929 /// This function will not block the calling thread and will only
1930 /// check to see if the child process has exited or not. If the child has
1931 /// exited then on Unix the process ID is reaped. This function is
1932 /// guaranteed to repeatedly return a successful exit status so long as the
1933 /// child has already exited.
1935 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1936 /// exit status is not available at this time then `Ok(None)` is returned.
1937 /// If an error occurs, then that error is returned.
1939 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1946 /// use std::process::Command;
1948 /// let mut child = Command::new("ls").spawn().unwrap();
1950 /// match child.try_wait() {
1951 /// Ok(Some(status)) => println!("exited with: {status}"),
1953 /// println!("status not ready yet, let's really wait");
1954 /// let res = child.wait();
1955 /// println!("result: {res:?}");
1957 /// Err(e) => println!("error attempting to wait: {e}"),
1960 #[stable(feature = "process_try_wait", since = "1.18.0")]
1961 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1962 Ok(self.handle.try_wait()?.map(ExitStatus))
1965 /// Simultaneously waits for the child to exit and collect all remaining
1966 /// output on the stdout/stderr handles, returning an `Output`
1969 /// The stdin handle to the child process, if any, will be closed
1970 /// before waiting. This helps avoid deadlock: it ensures that the
1971 /// child does not block waiting for input from the parent, while
1972 /// the parent waits for the child to exit.
1974 /// By default, stdin, stdout and stderr are inherited from the parent.
1975 /// In order to capture the output into this `Result<Output>` it is
1976 /// necessary to create new pipes between parent and child. Use
1977 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1982 /// use std::process::{Command, Stdio};
1984 /// let child = Command::new("/bin/cat")
1985 /// .arg("file.txt")
1986 /// .stdout(Stdio::piped())
1988 /// .expect("failed to execute child");
1990 /// let output = child
1991 /// .wait_with_output()
1992 /// .expect("failed to wait on child");
1994 /// assert!(output.status.success());
1997 #[stable(feature = "process", since = "1.0.0")]
1998 pub fn wait_with_output(mut self) -> io::Result<Output> {
1999 drop(self.stdin.take());
2001 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
2002 match (self.stdout.take(), self.stderr.take()) {
2004 (Some(mut out), None) => {
2005 let res = out.read_to_end(&mut stdout);
2008 (None, Some(mut err)) => {
2009 let res = err.read_to_end(&mut stderr);
2012 (Some(out), Some(err)) => {
2013 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
2018 let status = self.wait()?;
2019 Ok(Output { status, stdout, stderr })
2023 /// Terminates the current process with the specified exit code.
2025 /// This function will never return and will immediately terminate the current
2026 /// process. The exit code is passed through to the underlying OS and will be
2027 /// available for consumption by another process.
2029 /// Note that because this function never returns, and that it terminates the
2030 /// process, no destructors on the current stack or any other thread's stack
2031 /// will be run. If a clean shutdown is needed it is recommended to only call
2032 /// this function at a known point where there are no more destructors left
2033 /// to run; or, preferably, simply return a type implementing [`Termination`]
2034 /// (such as [`ExitCode`] or `Result`) from the `main` function and avoid this
2035 /// function altogether:
2038 /// # use std::io::Error as MyError;
2039 /// fn main() -> Result<(), MyError> {
2045 /// ## Platform-specific behavior
2047 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
2048 /// will be visible to a parent process inspecting the exit code. On most
2049 /// Unix-like platforms, only the eight least-significant bits are considered.
2051 /// For example, the exit code for this example will be `0` on Linux, but `256`
2055 /// use std::process;
2057 /// process::exit(0x0100);
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 pub fn exit(code: i32) -> ! {
2061 crate::rt::cleanup();
2062 crate::sys::os::exit(code)
2065 /// Terminates the process in an abnormal fashion.
2067 /// The function will never return and will immediately terminate the current
2068 /// process in a platform specific "abnormal" manner.
2070 /// Note that because this function never returns, and that it terminates the
2071 /// process, no destructors on the current stack or any other thread's stack
2074 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
2075 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
2077 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
2078 /// the current thread's stack and calls all destructors.
2079 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
2080 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
2081 /// [`panic!`] will still call the [panic hook] while `abort` will not.
2083 /// If a clean shutdown is needed it is recommended to only call
2084 /// this function at a known point where there are no more destructors left
2087 /// The process's termination will be similar to that from the C `abort()`
2088 /// function. On Unix, the process will terminate with signal `SIGABRT`, which
2089 /// typically means that the shell prints "Aborted".
2094 /// use std::process;
2097 /// println!("aborting");
2099 /// process::abort();
2101 /// // execution never gets here
2105 /// The `abort` function terminates the process, so the destructor will not
2106 /// get run on the example below:
2109 /// use std::process;
2113 /// impl Drop for HasDrop {
2114 /// fn drop(&mut self) {
2115 /// println!("This will never be printed!");
2120 /// let _x = HasDrop;
2121 /// process::abort();
2122 /// // the destructor implemented for HasDrop will never get run
2126 /// [panic hook]: crate::panic::set_hook
2127 #[stable(feature = "process_abort", since = "1.17.0")]
2129 pub fn abort() -> ! {
2130 crate::sys::abort_internal();
2133 /// Returns the OS-assigned process identifier associated with this process.
2140 /// use std::process;
2142 /// println!("My pid is {}", process::id());
2147 #[stable(feature = "getpid", since = "1.26.0")]
2148 pub fn id() -> u32 {
2149 crate::sys::os::getpid()
2152 /// A trait for implementing arbitrary return types in the `main` function.
2154 /// The C-main function only supports returning integers.
2155 /// So, every type implementing the `Termination` trait has to be converted
2158 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2159 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2161 /// Because different runtimes have different specifications on the return value
2162 /// of the `main` function, this trait is likely to be available only on
2163 /// standard library's runtime for convenience. Other runtimes are not required
2164 /// to provide similar functionality.
2165 #[cfg_attr(not(test), lang = "termination")]
2166 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2167 #[rustc_on_unimplemented(on(
2168 cause = "MainFunctionType",
2169 message = "`main` has invalid return type `{Self}`",
2170 label = "`main` can only return types that implement `{Termination}`"
2172 pub trait Termination {
2173 /// Is called to get the representation of the value as status code.
2174 /// This status code is returned to the operating system.
2175 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2176 fn report(self) -> ExitCode;
2179 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2180 impl Termination for () {
2182 fn report(self) -> ExitCode {
2187 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2188 impl Termination for ! {
2189 fn report(self) -> ExitCode {
2194 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2195 impl Termination for Infallible {
2196 fn report(self) -> ExitCode {
2201 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2202 impl Termination for ExitCode {
2204 fn report(self) -> ExitCode {
2209 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2210 impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
2211 fn report(self) -> ExitCode {
2213 Ok(val) => val.report(),
2215 io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));