1 //! A module for working with processes.
3 //! This module is mostly concerned with spawning and interacting with child
4 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
7 //! # Spawning a process
9 //! The [`Command`] struct is used to configure and spawn processes:
12 //! use std::process::Command;
14 //! let output = Command::new("echo")
15 //! .arg("Hello world")
17 //! .expect("Failed to execute command");
19 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
22 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
23 //! to spawn a process. In particular, [`output`] spawns the child process and
24 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
25 //! that represents the spawned child process.
29 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
30 //! configured by passing an [`Stdio`] to the corresponding method on
31 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
32 //! example, piping output from one command into another command can be done
36 //! use std::process::{Command, Stdio};
38 //! // stdout must be configured with `Stdio::piped` in order to use
39 //! // `echo_child.stdout`
40 //! let echo_child = Command::new("echo")
41 //! .arg("Oh no, a tpyo!")
42 //! .stdout(Stdio::piped())
44 //! .expect("Failed to start echo process");
46 //! // Note that `echo_child` is moved here, but we won't be needing
47 //! // `echo_child` anymore
48 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
50 //! let mut sed_child = Command::new("sed")
51 //! .arg("s/tpyo/typo/")
52 //! .stdin(Stdio::from(echo_out))
53 //! .stdout(Stdio::piped())
55 //! .expect("Failed to start sed process");
57 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
58 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
61 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
62 //! [`ChildStdin`] implements [`Write`]:
65 //! use std::process::{Command, Stdio};
66 //! use std::io::Write;
68 //! let mut child = Command::new("/bin/cat")
69 //! .stdin(Stdio::piped())
70 //! .stdout(Stdio::piped())
72 //! .expect("failed to execute child");
75 //! // limited borrow of stdin
76 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
77 //! stdin.write_all(b"test").expect("failed to write to stdin");
80 //! let output = child
81 //! .wait_with_output()
82 //! .expect("failed to wait on child");
84 //! assert_eq!(b"test", output.stdout.as_slice());
87 //! [`spawn`]: Command::spawn
88 //! [`output`]: Command::output
90 //! [`stdout`]: Command::stdout
91 //! [`stdin`]: Command::stdin
92 //! [`stderr`]: Command::stderr
94 //! [`Write`]: io::Write
95 //! [`Read`]: io::Read
97 #![stable(feature = "process", since = "1.0.0")]
98 #![deny(unsafe_op_in_unsafe_fn)]
100 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
103 use crate::io::prelude::*;
105 use crate::ffi::OsStr;
108 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
109 use crate::path::Path;
111 use crate::sys::pipe::{read2, AnonPipe};
112 use crate::sys::process as imp;
113 #[unstable(feature = "command_access", issue = "44434")]
114 pub use crate::sys_common::process::CommandEnvs;
115 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
117 /// Representation of a running or exited child process.
119 /// This structure is used to represent and manage child processes. A child
120 /// process is created via the [`Command`] struct, which configures the
121 /// spawning process and can itself be constructed using a builder-style
124 /// There is no implementation of [`Drop`] for child processes,
125 /// so if you do not ensure the `Child` has exited then it will continue to
126 /// run, even after the `Child` handle to the child process has gone out of
129 /// Calling [`wait`] (or other functions that wrap around it) will make
130 /// the parent process wait until the child has actually exited before
135 /// On some systems, calling [`wait`] or similar is necessary for the OS to
136 /// release resources. A process that terminated but has not been waited on is
137 /// still around as a "zombie". Leaving too many zombies around may exhaust
138 /// global resources (for example process IDs).
140 /// The standard library does *not* automatically wait on child processes (not
141 /// even if the `Child` is dropped), it is up to the application developer to do
142 /// so. As a consequence, dropping `Child` handles without waiting on them first
143 /// is not recommended in long-running applications.
148 /// use std::process::Command;
150 /// let mut child = Command::new("/bin/cat")
153 /// .expect("failed to execute child");
155 /// let ecode = child.wait()
156 /// .expect("failed to wait on child");
158 /// assert!(ecode.success());
161 /// [`wait`]: Child::wait
162 #[stable(feature = "process", since = "1.0.0")]
164 handle: imp::Process,
166 /// The handle for writing to the child's standard input (stdin), if it has
167 /// been captured. To avoid partially moving
168 /// the `child` and thus blocking yourself from calling
169 /// functions on `child` while using `stdin`,
170 /// you might find it helpful:
172 /// ```compile_fail,E0425
173 /// let stdin = child.stdin.take().unwrap();
175 #[stable(feature = "process", since = "1.0.0")]
176 pub stdin: Option<ChildStdin>,
178 /// The handle for reading from the child's standard output (stdout), if it
179 /// has been captured. You might find it helpful to do
181 /// ```compile_fail,E0425
182 /// let stdout = child.stdout.take().unwrap();
185 /// to avoid partially moving the `child` and thus blocking yourself from calling
186 /// functions on `child` while using `stdout`.
187 #[stable(feature = "process", since = "1.0.0")]
188 pub stdout: Option<ChildStdout>,
190 /// The handle for reading from the child's standard error (stderr), if it
191 /// has been captured. You might find it helpful to do
193 /// ```compile_fail,E0425
194 /// let stderr = child.stderr.take().unwrap();
197 /// to avoid partially moving the `child` and thus blocking yourself from calling
198 /// functions on `child` while using `stderr`.
199 #[stable(feature = "process", since = "1.0.0")]
200 pub stderr: Option<ChildStderr>,
203 impl AsInner<imp::Process> for Child {
204 fn as_inner(&self) -> &imp::Process {
209 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
210 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
213 stdin: io.stdin.map(ChildStdin::from_inner),
214 stdout: io.stdout.map(ChildStdout::from_inner),
215 stderr: io.stderr.map(ChildStderr::from_inner),
220 impl IntoInner<imp::Process> for Child {
221 fn into_inner(self) -> imp::Process {
226 #[stable(feature = "std_debug", since = "1.16.0")]
227 impl fmt::Debug for Child {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.debug_struct("Child")
230 .field("stdin", &self.stdin)
231 .field("stdout", &self.stdout)
232 .field("stderr", &self.stderr)
237 /// A handle to a child process's standard input (stdin).
239 /// This struct is used in the [`stdin`] field on [`Child`].
241 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
242 /// file handle will be closed. If the child process was blocked on input prior
243 /// to being dropped, it will become unblocked after dropping.
245 /// [`stdin`]: Child::stdin
247 #[stable(feature = "process", since = "1.0.0")]
248 pub struct ChildStdin {
252 #[stable(feature = "process", since = "1.0.0")]
253 impl Write for ChildStdin {
254 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
258 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
259 (&*self).write_vectored(bufs)
262 fn is_write_vectored(&self) -> bool {
263 io::Write::is_write_vectored(&&*self)
266 fn flush(&mut self) -> io::Result<()> {
271 #[stable(feature = "write_mt", since = "1.48.0")]
272 impl Write for &ChildStdin {
273 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
274 self.inner.write(buf)
277 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
278 self.inner.write_vectored(bufs)
281 fn is_write_vectored(&self) -> bool {
282 self.inner.is_write_vectored()
285 fn flush(&mut self) -> io::Result<()> {
290 impl AsInner<AnonPipe> for ChildStdin {
291 fn as_inner(&self) -> &AnonPipe {
296 impl IntoInner<AnonPipe> for ChildStdin {
297 fn into_inner(self) -> AnonPipe {
302 impl FromInner<AnonPipe> for ChildStdin {
303 fn from_inner(pipe: AnonPipe) -> ChildStdin {
304 ChildStdin { inner: pipe }
308 #[stable(feature = "std_debug", since = "1.16.0")]
309 impl fmt::Debug for ChildStdin {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 f.pad("ChildStdin { .. }")
315 /// A handle to a child process's standard output (stdout).
317 /// This struct is used in the [`stdout`] field on [`Child`].
319 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
320 /// underlying file handle will be closed.
322 /// [`stdout`]: Child::stdout
324 #[stable(feature = "process", since = "1.0.0")]
325 pub struct ChildStdout {
329 #[stable(feature = "process", since = "1.0.0")]
330 impl Read for ChildStdout {
331 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
335 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
336 self.inner.read_vectored(bufs)
340 fn is_read_vectored(&self) -> bool {
341 self.inner.is_read_vectored()
345 unsafe fn initializer(&self) -> Initializer {
346 // SAFETY: Read is guaranteed to work on uninitialized memory
347 unsafe { Initializer::nop() }
351 impl AsInner<AnonPipe> for ChildStdout {
352 fn as_inner(&self) -> &AnonPipe {
357 impl IntoInner<AnonPipe> for ChildStdout {
358 fn into_inner(self) -> AnonPipe {
363 impl FromInner<AnonPipe> for ChildStdout {
364 fn from_inner(pipe: AnonPipe) -> ChildStdout {
365 ChildStdout { inner: pipe }
369 #[stable(feature = "std_debug", since = "1.16.0")]
370 impl fmt::Debug for ChildStdout {
371 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372 f.pad("ChildStdout { .. }")
376 /// A handle to a child process's stderr.
378 /// This struct is used in the [`stderr`] field on [`Child`].
380 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
381 /// underlying file handle will be closed.
383 /// [`stderr`]: Child::stderr
385 #[stable(feature = "process", since = "1.0.0")]
386 pub struct ChildStderr {
390 #[stable(feature = "process", since = "1.0.0")]
391 impl Read for ChildStderr {
392 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
396 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
397 self.inner.read_vectored(bufs)
401 fn is_read_vectored(&self) -> bool {
402 self.inner.is_read_vectored()
406 unsafe fn initializer(&self) -> Initializer {
407 // SAFETY: Read is guaranteed to work on uninitialized memory
408 unsafe { Initializer::nop() }
412 impl AsInner<AnonPipe> for ChildStderr {
413 fn as_inner(&self) -> &AnonPipe {
418 impl IntoInner<AnonPipe> for ChildStderr {
419 fn into_inner(self) -> AnonPipe {
424 impl FromInner<AnonPipe> for ChildStderr {
425 fn from_inner(pipe: AnonPipe) -> ChildStderr {
426 ChildStderr { inner: pipe }
430 #[stable(feature = "std_debug", since = "1.16.0")]
431 impl fmt::Debug for ChildStderr {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 f.pad("ChildStderr { .. }")
437 /// A process builder, providing fine-grained control
438 /// over how a new process should be spawned.
440 /// A default configuration can be
441 /// generated using `Command::new(program)`, where `program` gives a path to the
442 /// program to be executed. Additional builder methods allow the configuration
443 /// to be changed (for example, by adding arguments) prior to spawning:
446 /// use std::process::Command;
448 /// let output = if cfg!(target_os = "windows") {
449 /// Command::new("cmd")
450 /// .args(&["/C", "echo hello"])
452 /// .expect("failed to execute process")
454 /// Command::new("sh")
456 /// .arg("echo hello")
458 /// .expect("failed to execute process")
461 /// let hello = output.stdout;
464 /// `Command` can be reused to spawn multiple processes. The builder methods
465 /// change the command without needing to immediately spawn the process.
468 /// use std::process::Command;
470 /// let mut echo_hello = Command::new("sh");
471 /// echo_hello.arg("-c")
472 /// .arg("echo hello");
473 /// let hello_1 = echo_hello.output().expect("failed to execute process");
474 /// let hello_2 = echo_hello.output().expect("failed to execute process");
477 /// Similarly, you can call builder methods after spawning a process and then
478 /// spawn a new process with the modified settings.
481 /// use std::process::Command;
483 /// let mut list_dir = Command::new("ls");
485 /// // Execute `ls` in the current directory of the program.
486 /// list_dir.status().expect("process failed to execute");
490 /// // Change `ls` to execute in the root directory.
491 /// list_dir.current_dir("/");
493 /// // And then execute `ls` again but in the root directory.
494 /// list_dir.status().expect("process failed to execute");
496 #[stable(feature = "process", since = "1.0.0")]
502 /// Constructs a new `Command` for launching the program at
503 /// path `program`, with the following default configuration:
505 /// * No arguments to the program
506 /// * Inherit the current process's environment
507 /// * Inherit the current process's working directory
508 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
510 /// Builder methods are provided to change these defaults and
511 /// otherwise configure the process.
513 /// If `program` is not an absolute path, the `PATH` will be searched in
514 /// an OS-defined way.
516 /// The search path to be used may be controlled by setting the
517 /// `PATH` environment variable on the Command,
518 /// but this has some implementation limitations on Windows
519 /// (see issue #37519).
526 /// use std::process::Command;
528 /// Command::new("sh")
530 /// .expect("sh command failed to start");
532 #[stable(feature = "process", since = "1.0.0")]
533 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
534 Command { inner: imp::Command::new(program.as_ref()) }
537 /// Adds an argument to pass to the program.
539 /// Only one argument can be passed per use. So instead of:
542 /// # std::process::Command::new("sh")
543 /// .arg("-C /path/to/repo")
550 /// # std::process::Command::new("sh")
552 /// .arg("/path/to/repo")
556 /// To pass multiple arguments see [`args`].
558 /// [`args`]: Command::args
560 /// Note that the argument is not passed through a shell, but given
561 /// literally to the program. This means that shell syntax like quotes,
562 /// escaped characters, word splitting, glob patterns, substitution, etc.
570 /// use std::process::Command;
572 /// Command::new("ls")
576 /// .expect("ls command failed to start");
578 #[stable(feature = "process", since = "1.0.0")]
579 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
580 self.inner.arg(arg.as_ref());
584 /// Adds multiple arguments to pass to the program.
586 /// To pass a single argument see [`arg`].
588 /// [`arg`]: Command::arg
590 /// Note that the arguments are not passed through a shell, but given
591 /// literally to the program. This means that shell syntax like quotes,
592 /// escaped characters, word splitting, glob patterns, substitution, etc.
600 /// use std::process::Command;
602 /// Command::new("ls")
603 /// .args(&["-l", "-a"])
605 /// .expect("ls command failed to start");
607 #[stable(feature = "process", since = "1.0.0")]
608 pub fn args<I, S>(&mut self, args: I) -> &mut Command
610 I: IntoIterator<Item = S>,
614 self.arg(arg.as_ref());
619 /// Inserts or updates an environment variable mapping.
621 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
622 /// and case-sensitive on all other platforms.
629 /// use std::process::Command;
631 /// Command::new("ls")
632 /// .env("PATH", "/bin")
634 /// .expect("ls command failed to start");
636 #[stable(feature = "process", since = "1.0.0")]
637 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
642 self.inner.env_mut().set(key.as_ref(), val.as_ref());
646 /// Adds or updates multiple environment variable mappings.
653 /// use std::process::{Command, Stdio};
655 /// use std::collections::HashMap;
657 /// let filtered_env : HashMap<String, String> =
658 /// env::vars().filter(|&(ref k, _)|
659 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
662 /// Command::new("printenv")
663 /// .stdin(Stdio::null())
664 /// .stdout(Stdio::inherit())
666 /// .envs(&filtered_env)
668 /// .expect("printenv failed to start");
670 #[stable(feature = "command_envs", since = "1.19.0")]
671 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
673 I: IntoIterator<Item = (K, V)>,
677 for (ref key, ref val) in vars {
678 self.inner.env_mut().set(key.as_ref(), val.as_ref());
683 /// Removes an environment variable mapping.
690 /// use std::process::Command;
692 /// Command::new("ls")
693 /// .env_remove("PATH")
695 /// .expect("ls command failed to start");
697 #[stable(feature = "process", since = "1.0.0")]
698 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
699 self.inner.env_mut().remove(key.as_ref());
703 /// Clears the entire environment map for the child process.
710 /// use std::process::Command;
712 /// Command::new("ls")
715 /// .expect("ls command failed to start");
717 #[stable(feature = "process", since = "1.0.0")]
718 pub fn env_clear(&mut self) -> &mut Command {
719 self.inner.env_mut().clear();
723 /// Sets the working directory for the child process.
725 /// # Platform-specific behavior
727 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
728 /// whether it should be interpreted relative to the parent's working
729 /// directory or relative to `current_dir`. The behavior in this case is
730 /// platform specific and unstable, and it's recommended to use
731 /// [`canonicalize`] to get an absolute program path instead.
738 /// use std::process::Command;
740 /// Command::new("ls")
741 /// .current_dir("/bin")
743 /// .expect("ls command failed to start");
746 /// [`canonicalize`]: crate::fs::canonicalize
747 #[stable(feature = "process", since = "1.0.0")]
748 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
749 self.inner.cwd(dir.as_ref().as_ref());
753 /// Configuration for the child process's standard input (stdin) handle.
755 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
756 /// defaults to [`piped`] when used with `output`.
758 /// [`inherit`]: Stdio::inherit
759 /// [`piped`]: Stdio::piped
766 /// use std::process::{Command, Stdio};
768 /// Command::new("ls")
769 /// .stdin(Stdio::null())
771 /// .expect("ls command failed to start");
773 #[stable(feature = "process", since = "1.0.0")]
774 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
775 self.inner.stdin(cfg.into().0);
779 /// Configuration for the child process's standard output (stdout) handle.
781 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
782 /// defaults to [`piped`] when used with `output`.
784 /// [`inherit`]: Stdio::inherit
785 /// [`piped`]: Stdio::piped
792 /// use std::process::{Command, Stdio};
794 /// Command::new("ls")
795 /// .stdout(Stdio::null())
797 /// .expect("ls command failed to start");
799 #[stable(feature = "process", since = "1.0.0")]
800 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
801 self.inner.stdout(cfg.into().0);
805 /// Configuration for the child process's standard error (stderr) handle.
807 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
808 /// defaults to [`piped`] when used with `output`.
810 /// [`inherit`]: Stdio::inherit
811 /// [`piped`]: Stdio::piped
818 /// use std::process::{Command, Stdio};
820 /// Command::new("ls")
821 /// .stderr(Stdio::null())
823 /// .expect("ls command failed to start");
825 #[stable(feature = "process", since = "1.0.0")]
826 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
827 self.inner.stderr(cfg.into().0);
831 /// Executes the command as a child process, returning a handle to it.
833 /// By default, stdin, stdout and stderr are inherited from the parent.
840 /// use std::process::Command;
842 /// Command::new("ls")
844 /// .expect("ls command failed to start");
846 #[stable(feature = "process", since = "1.0.0")]
847 pub fn spawn(&mut self) -> io::Result<Child> {
848 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
851 /// Executes the command as a child process, waiting for it to finish and
852 /// collecting all of its output.
854 /// By default, stdout and stderr are captured (and used to provide the
855 /// resulting output). Stdin is not inherited from the parent and any
856 /// attempt by the child process to read from the stdin stream will result
857 /// in the stream immediately closing.
862 /// use std::process::Command;
863 /// use std::io::{self, Write};
864 /// let output = Command::new("/bin/cat")
867 /// .expect("failed to execute process");
869 /// println!("status: {}", output.status);
870 /// io::stdout().write_all(&output.stdout).unwrap();
871 /// io::stderr().write_all(&output.stderr).unwrap();
873 /// assert!(output.status.success());
875 #[stable(feature = "process", since = "1.0.0")]
876 pub fn output(&mut self) -> io::Result<Output> {
878 .spawn(imp::Stdio::MakePipe, false)
879 .map(Child::from_inner)
880 .and_then(|p| p.wait_with_output())
883 /// Executes a command as a child process, waiting for it to finish and
884 /// collecting its exit status.
886 /// By default, stdin, stdout and stderr are inherited from the parent.
891 /// use std::process::Command;
893 /// let status = Command::new("/bin/cat")
896 /// .expect("failed to execute process");
898 /// println!("process exited with: {}", status);
900 /// assert!(status.success());
902 #[stable(feature = "process", since = "1.0.0")]
903 pub fn status(&mut self) -> io::Result<ExitStatus> {
905 .spawn(imp::Stdio::Inherit, true)
906 .map(Child::from_inner)
907 .and_then(|mut p| p.wait())
910 /// Returns the path to the program that was given to [`Command::new`].
915 /// # #![feature(command_access)]
916 /// use std::process::Command;
918 /// let cmd = Command::new("echo");
919 /// assert_eq!(cmd.get_program(), "echo");
921 #[unstable(feature = "command_access", issue = "44434")]
922 pub fn get_program(&self) -> &OsStr {
923 self.inner.get_program()
926 /// Returns an iterator of the arguments that will be passed to the program.
928 /// This does not include the path to the program as the first argument;
929 /// it only includes the arguments specified with [`Command::arg`] and
930 /// [`Command::args`].
935 /// # #![feature(command_access)]
936 /// use std::ffi::OsStr;
937 /// use std::process::Command;
939 /// let mut cmd = Command::new("echo");
940 /// cmd.arg("first").arg("second");
941 /// let args: Vec<&OsStr> = cmd.get_args().collect();
942 /// assert_eq!(args, &["first", "second"]);
944 #[unstable(feature = "command_access", issue = "44434")]
945 pub fn get_args(&self) -> CommandArgs<'_> {
946 CommandArgs { inner: self.inner.get_args() }
949 /// Returns an iterator of the environment variables that will be set when
950 /// the process is spawned.
952 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
953 /// value is the key, and the second is the value, which is [`None`] if
954 /// the environment variable is to be explicitly removed.
956 /// This only includes environment variables explicitly set with
957 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
958 /// does not include environment variables that will be inherited by the
964 /// # #![feature(command_access)]
965 /// use std::ffi::OsStr;
966 /// use std::process::Command;
968 /// let mut cmd = Command::new("ls");
969 /// cmd.env("TERM", "dumb").env_remove("TZ");
970 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
971 /// assert_eq!(envs, &[
972 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
973 /// (OsStr::new("TZ"), None)
976 #[unstable(feature = "command_access", issue = "44434")]
977 pub fn get_envs(&self) -> CommandEnvs<'_> {
978 self.inner.get_envs()
981 /// Returns the working directory for the child process.
983 /// This returns [`None`] if the working directory will not be changed.
988 /// # #![feature(command_access)]
989 /// use std::path::Path;
990 /// use std::process::Command;
992 /// let mut cmd = Command::new("ls");
993 /// assert_eq!(cmd.get_current_dir(), None);
994 /// cmd.current_dir("/bin");
995 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
997 #[unstable(feature = "command_access", issue = "44434")]
998 pub fn get_current_dir(&self) -> Option<&Path> {
999 self.inner.get_current_dir()
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 impl fmt::Debug for Command {
1005 /// Format the program and arguments of a Command for display. Any
1006 /// non-utf8 data is lossily converted using the utf8 replacement
1008 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013 impl AsInner<imp::Command> for Command {
1014 fn as_inner(&self) -> &imp::Command {
1019 impl AsInnerMut<imp::Command> for Command {
1020 fn as_inner_mut(&mut self) -> &mut imp::Command {
1025 /// An iterator over the command arguments.
1027 /// This struct is created by [`Command::get_args`]. See its documentation for
1029 #[unstable(feature = "command_access", issue = "44434")]
1031 pub struct CommandArgs<'a> {
1032 inner: imp::CommandArgs<'a>,
1035 #[unstable(feature = "command_access", issue = "44434")]
1036 impl<'a> Iterator for CommandArgs<'a> {
1037 type Item = &'a OsStr;
1038 fn next(&mut self) -> Option<&'a OsStr> {
1041 fn size_hint(&self) -> (usize, Option<usize>) {
1042 self.inner.size_hint()
1046 #[unstable(feature = "command_access", issue = "44434")]
1047 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1048 fn len(&self) -> usize {
1051 fn is_empty(&self) -> bool {
1052 self.inner.is_empty()
1056 /// The output of a finished process.
1058 /// This is returned in a Result by either the [`output`] method of a
1059 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1062 /// [`output`]: Command::output
1063 /// [`wait_with_output`]: Child::wait_with_output
1064 #[derive(PartialEq, Eq, Clone)]
1065 #[stable(feature = "process", since = "1.0.0")]
1067 /// The status (exit code) of the process.
1068 #[stable(feature = "process", since = "1.0.0")]
1069 pub status: ExitStatus,
1070 /// The data that the process wrote to stdout.
1071 #[stable(feature = "process", since = "1.0.0")]
1072 pub stdout: Vec<u8>,
1073 /// The data that the process wrote to stderr.
1074 #[stable(feature = "process", since = "1.0.0")]
1075 pub stderr: Vec<u8>,
1078 // If either stderr or stdout are valid utf8 strings it prints the valid
1079 // strings, otherwise it prints the byte sequence instead
1080 #[stable(feature = "process_output_debug", since = "1.7.0")]
1081 impl fmt::Debug for Output {
1082 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1083 let stdout_utf8 = str::from_utf8(&self.stdout);
1084 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1086 Err(_) => &self.stdout,
1089 let stderr_utf8 = str::from_utf8(&self.stderr);
1090 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1092 Err(_) => &self.stderr,
1095 fmt.debug_struct("Output")
1096 .field("status", &self.status)
1097 .field("stdout", stdout_debug)
1098 .field("stderr", stderr_debug)
1103 /// Describes what to do with a standard I/O stream for a child process when
1104 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1106 /// [`stdin`]: Command::stdin
1107 /// [`stdout`]: Command::stdout
1108 /// [`stderr`]: Command::stderr
1109 #[stable(feature = "process", since = "1.0.0")]
1110 pub struct Stdio(imp::Stdio);
1113 /// A new pipe should be arranged to connect the parent and child processes.
1120 /// use std::process::{Command, Stdio};
1122 /// let output = Command::new("echo")
1123 /// .arg("Hello, world!")
1124 /// .stdout(Stdio::piped())
1126 /// .expect("Failed to execute command");
1128 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1129 /// // Nothing echoed to console
1135 /// use std::io::Write;
1136 /// use std::process::{Command, Stdio};
1138 /// let mut child = Command::new("rev")
1139 /// .stdin(Stdio::piped())
1140 /// .stdout(Stdio::piped())
1142 /// .expect("Failed to spawn child process");
1145 /// let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1146 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1149 /// let output = child.wait_with_output().expect("Failed to read stdout");
1150 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1152 #[stable(feature = "process", since = "1.0.0")]
1153 pub fn piped() -> Stdio {
1154 Stdio(imp::Stdio::MakePipe)
1157 /// The child inherits from the corresponding parent descriptor.
1164 /// use std::process::{Command, Stdio};
1166 /// let output = Command::new("echo")
1167 /// .arg("Hello, world!")
1168 /// .stdout(Stdio::inherit())
1170 /// .expect("Failed to execute command");
1172 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1173 /// // "Hello, world!" echoed to console
1179 /// use std::process::{Command, Stdio};
1180 /// use std::io::{self, Write};
1182 /// let output = Command::new("rev")
1183 /// .stdin(Stdio::inherit())
1184 /// .stdout(Stdio::piped())
1186 /// .expect("Failed to execute command");
1188 /// print!("You piped in the reverse of: ");
1189 /// io::stdout().write_all(&output.stdout).unwrap();
1191 #[stable(feature = "process", since = "1.0.0")]
1192 pub fn inherit() -> Stdio {
1193 Stdio(imp::Stdio::Inherit)
1196 /// This stream will be ignored. This is the equivalent of attaching the
1197 /// stream to `/dev/null`.
1204 /// use std::process::{Command, Stdio};
1206 /// let output = Command::new("echo")
1207 /// .arg("Hello, world!")
1208 /// .stdout(Stdio::null())
1210 /// .expect("Failed to execute command");
1212 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1213 /// // Nothing echoed to console
1219 /// use std::process::{Command, Stdio};
1221 /// let output = Command::new("rev")
1222 /// .stdin(Stdio::null())
1223 /// .stdout(Stdio::piped())
1225 /// .expect("Failed to execute command");
1227 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1228 /// // Ignores any piped-in input
1230 #[stable(feature = "process", since = "1.0.0")]
1231 pub fn null() -> Stdio {
1232 Stdio(imp::Stdio::Null)
1236 impl FromInner<imp::Stdio> for Stdio {
1237 fn from_inner(inner: imp::Stdio) -> Stdio {
1242 #[stable(feature = "std_debug", since = "1.16.0")]
1243 impl fmt::Debug for Stdio {
1244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245 f.pad("Stdio { .. }")
1249 #[stable(feature = "stdio_from", since = "1.20.0")]
1250 impl From<ChildStdin> for Stdio {
1251 /// Converts a `ChildStdin` into a `Stdio`
1255 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1258 /// use std::process::{Command, Stdio};
1260 /// let reverse = Command::new("rev")
1261 /// .stdin(Stdio::piped())
1263 /// .expect("failed reverse command");
1265 /// let _echo = Command::new("echo")
1266 /// .arg("Hello, world!")
1267 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1269 /// .expect("failed echo command");
1271 /// // "!dlrow ,olleH" echoed to console
1273 fn from(child: ChildStdin) -> Stdio {
1274 Stdio::from_inner(child.into_inner().into())
1278 #[stable(feature = "stdio_from", since = "1.20.0")]
1279 impl From<ChildStdout> for Stdio {
1280 /// Converts a `ChildStdout` into a `Stdio`
1284 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1287 /// use std::process::{Command, Stdio};
1289 /// let hello = Command::new("echo")
1290 /// .arg("Hello, world!")
1291 /// .stdout(Stdio::piped())
1293 /// .expect("failed echo command");
1295 /// let reverse = Command::new("rev")
1296 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1298 /// .expect("failed reverse command");
1300 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1302 fn from(child: ChildStdout) -> Stdio {
1303 Stdio::from_inner(child.into_inner().into())
1307 #[stable(feature = "stdio_from", since = "1.20.0")]
1308 impl From<ChildStderr> for Stdio {
1309 /// Converts a `ChildStderr` into a `Stdio`
1314 /// use std::process::{Command, Stdio};
1316 /// let reverse = Command::new("rev")
1317 /// .arg("non_existing_file.txt")
1318 /// .stderr(Stdio::piped())
1320 /// .expect("failed reverse command");
1322 /// let cat = Command::new("cat")
1324 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1326 /// .expect("failed echo command");
1329 /// String::from_utf8_lossy(&cat.stdout),
1330 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1333 fn from(child: ChildStderr) -> Stdio {
1334 Stdio::from_inner(child.into_inner().into())
1338 #[stable(feature = "stdio_from", since = "1.20.0")]
1339 impl From<fs::File> for Stdio {
1340 /// Converts a `File` into a `Stdio`
1344 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1347 /// use std::fs::File;
1348 /// use std::process::Command;
1350 /// // With the `foo.txt` file containing `Hello, world!"
1351 /// let file = File::open("foo.txt").unwrap();
1353 /// let reverse = Command::new("rev")
1354 /// .stdin(file) // Implicit File conversion into a Stdio
1356 /// .expect("failed reverse command");
1358 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1360 fn from(file: fs::File) -> Stdio {
1361 Stdio::from_inner(file.into_inner().into())
1365 /// Describes the result of a process after it has terminated.
1367 /// This `struct` is used to represent the exit status of a child process.
1368 /// Child processes are created via the [`Command`] struct and their exit
1369 /// status is exposed through the [`status`] method, or the [`wait`] method
1370 /// of a [`Child`] process.
1372 /// [`status`]: Command::status
1373 /// [`wait`]: Child::wait
1374 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1375 #[stable(feature = "process", since = "1.0.0")]
1376 pub struct ExitStatus(imp::ExitStatus);
1379 /// Was termination successful? Signal termination is not considered a
1380 /// success, and success is defined as a zero exit status.
1385 /// use std::process::Command;
1387 /// let status = Command::new("mkdir")
1388 /// .arg("projects")
1390 /// .expect("failed to execute mkdir");
1392 /// if status.success() {
1393 /// println!("'projects/' directory created");
1395 /// println!("failed to create 'projects/' directory");
1398 #[stable(feature = "process", since = "1.0.0")]
1399 pub fn success(&self) -> bool {
1403 /// Returns the exit code of the process, if any.
1405 /// On Unix, this will return `None` if the process was terminated
1406 /// by a signal; `std::os::unix` provides an extension trait for
1407 /// extracting the signal and other details from the `ExitStatus`.
1412 /// use std::process::Command;
1414 /// let status = Command::new("mkdir")
1415 /// .arg("projects")
1417 /// .expect("failed to execute mkdir");
1419 /// match status.code() {
1420 /// Some(code) => println!("Exited with status code: {}", code),
1421 /// None => println!("Process terminated by signal")
1424 #[stable(feature = "process", since = "1.0.0")]
1425 pub fn code(&self) -> Option<i32> {
1430 impl AsInner<imp::ExitStatus> for ExitStatus {
1431 fn as_inner(&self) -> &imp::ExitStatus {
1436 impl FromInner<imp::ExitStatus> for ExitStatus {
1437 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1442 #[stable(feature = "process", since = "1.0.0")]
1443 impl fmt::Display for ExitStatus {
1444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1449 /// This type represents the status code a process can return to its
1450 /// parent under normal termination.
1452 /// Numeric values used in this type don't have portable meanings, and
1453 /// different platforms may mask different amounts of them.
1455 /// For the platform's canonical successful and unsuccessful codes, see
1456 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1458 /// [`SUCCESS`]: ExitCode::SUCCESS
1459 /// [`FAILURE`]: ExitCode::FAILURE
1461 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1462 /// it was ultimately cut from that RFC, and thus this type is more subject
1463 /// to change even than the usual unstable item churn.
1465 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1466 #[derive(Clone, Copy, Debug)]
1467 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1468 pub struct ExitCode(imp::ExitCode);
1470 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1472 /// The canonical ExitCode for successful termination on this platform.
1474 /// Note that a `()`-returning `main` implicitly results in a successful
1475 /// termination, so there's no need to return this from `main` unless
1476 /// you're also returning other possible codes.
1477 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1478 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1480 /// The canonical ExitCode for unsuccessful termination on this platform.
1482 /// If you're only returning this and `SUCCESS` from `main`, consider
1483 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1484 /// return the same codes (but will also `eprintln!` the error).
1485 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1486 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1490 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1491 /// error is returned.
1493 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1494 /// especially the [`Other`] kind might change to more specific kinds in the future.
1496 /// This is equivalent to sending a SIGKILL on Unix platforms.
1503 /// use std::process::Command;
1505 /// let mut command = Command::new("yes");
1506 /// if let Ok(mut child) = command.spawn() {
1507 /// child.kill().expect("command wasn't running");
1509 /// println!("yes command didn't start");
1513 /// [`ErrorKind`]: io::ErrorKind
1514 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1515 /// [`Other`]: io::ErrorKind::Other
1516 #[stable(feature = "process", since = "1.0.0")]
1517 pub fn kill(&mut self) -> io::Result<()> {
1521 /// Returns the OS-assigned process identifier associated with this child.
1528 /// use std::process::Command;
1530 /// let mut command = Command::new("ls");
1531 /// if let Ok(child) = command.spawn() {
1532 /// println!("Child's ID is {}", child.id());
1534 /// println!("ls command didn't start");
1537 #[stable(feature = "process_id", since = "1.3.0")]
1538 pub fn id(&self) -> u32 {
1542 /// Waits for the child to exit completely, returning the status that it
1543 /// exited with. This function will continue to have the same return value
1544 /// after it has been called at least once.
1546 /// The stdin handle to the child process, if any, will be closed
1547 /// before waiting. This helps avoid deadlock: it ensures that the
1548 /// child does not block waiting for input from the parent, while
1549 /// the parent waits for the child to exit.
1556 /// use std::process::Command;
1558 /// let mut command = Command::new("ls");
1559 /// if let Ok(mut child) = command.spawn() {
1560 /// child.wait().expect("command wasn't running");
1561 /// println!("Child has finished its execution!");
1563 /// println!("ls command didn't start");
1566 #[stable(feature = "process", since = "1.0.0")]
1567 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1568 drop(self.stdin.take());
1569 self.handle.wait().map(ExitStatus)
1572 /// Attempts to collect the exit status of the child if it has already
1575 /// This function will not block the calling thread and will only
1576 /// check to see if the child process has exited or not. If the child has
1577 /// exited then on Unix the process ID is reaped. This function is
1578 /// guaranteed to repeatedly return a successful exit status so long as the
1579 /// child has already exited.
1581 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1582 /// exit status is not available at this time then `Ok(None)` is returned.
1583 /// If an error occurs, then that error is returned.
1585 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1592 /// use std::process::Command;
1594 /// let mut child = Command::new("ls").spawn().unwrap();
1596 /// match child.try_wait() {
1597 /// Ok(Some(status)) => println!("exited with: {}", status),
1599 /// println!("status not ready yet, let's really wait");
1600 /// let res = child.wait();
1601 /// println!("result: {:?}", res);
1603 /// Err(e) => println!("error attempting to wait: {}", e),
1606 #[stable(feature = "process_try_wait", since = "1.18.0")]
1607 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1608 Ok(self.handle.try_wait()?.map(ExitStatus))
1611 /// Simultaneously waits for the child to exit and collect all remaining
1612 /// output on the stdout/stderr handles, returning an `Output`
1615 /// The stdin handle to the child process, if any, will be closed
1616 /// before waiting. This helps avoid deadlock: it ensures that the
1617 /// child does not block waiting for input from the parent, while
1618 /// the parent waits for the child to exit.
1620 /// By default, stdin, stdout and stderr are inherited from the parent.
1621 /// In order to capture the output into this `Result<Output>` it is
1622 /// necessary to create new pipes between parent and child. Use
1623 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1628 /// use std::process::{Command, Stdio};
1630 /// let child = Command::new("/bin/cat")
1631 /// .arg("file.txt")
1632 /// .stdout(Stdio::piped())
1634 /// .expect("failed to execute child");
1636 /// let output = child
1637 /// .wait_with_output()
1638 /// .expect("failed to wait on child");
1640 /// assert!(output.status.success());
1643 #[stable(feature = "process", since = "1.0.0")]
1644 pub fn wait_with_output(mut self) -> io::Result<Output> {
1645 drop(self.stdin.take());
1647 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1648 match (self.stdout.take(), self.stderr.take()) {
1650 (Some(mut out), None) => {
1651 let res = out.read_to_end(&mut stdout);
1654 (None, Some(mut err)) => {
1655 let res = err.read_to_end(&mut stderr);
1658 (Some(out), Some(err)) => {
1659 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1664 let status = self.wait()?;
1665 Ok(Output { status, stdout, stderr })
1669 /// Terminates the current process with the specified exit code.
1671 /// This function will never return and will immediately terminate the current
1672 /// process. The exit code is passed through to the underlying OS and will be
1673 /// available for consumption by another process.
1675 /// Note that because this function never returns, and that it terminates the
1676 /// process, no destructors on the current stack or any other thread's stack
1677 /// will be run. If a clean shutdown is needed it is recommended to only call
1678 /// this function at a known point where there are no more destructors left
1681 /// ## Platform-specific behavior
1683 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1684 /// will be visible to a parent process inspecting the exit code. On most
1685 /// Unix-like platforms, only the eight least-significant bits are considered.
1689 /// Due to this function’s behavior regarding destructors, a conventional way
1690 /// to use the function is to extract the actual computation to another
1691 /// function and compute the exit code from its return value:
1694 /// fn run_app() -> Result<(), ()> {
1695 /// // Application logic here
1700 /// std::process::exit(match run_app() {
1703 /// eprintln!("error: {:?}", err);
1710 /// Due to [platform-specific behavior], the exit code for this example will be
1711 /// `0` on Linux, but `256` on Windows:
1714 /// use std::process;
1716 /// process::exit(0x0100);
1719 /// [platform-specific behavior]: #platform-specific-behavior
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 pub fn exit(code: i32) -> ! {
1722 crate::sys_common::cleanup();
1723 crate::sys::os::exit(code)
1726 /// Terminates the process in an abnormal fashion.
1728 /// The function will never return and will immediately terminate the current
1729 /// process in a platform specific "abnormal" manner.
1731 /// Note that because this function never returns, and that it terminates the
1732 /// process, no destructors on the current stack or any other thread's stack
1735 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1736 /// the current thread's stack and calls all destructors.
1737 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1738 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1739 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1741 /// If a clean shutdown is needed it is recommended to only call
1742 /// this function at a known point where there are no more destructors left
1748 /// use std::process;
1751 /// println!("aborting");
1753 /// process::abort();
1755 /// // execution never gets here
1759 /// The `abort` function terminates the process, so the destructor will not
1760 /// get run on the example below:
1763 /// use std::process;
1767 /// impl Drop for HasDrop {
1768 /// fn drop(&mut self) {
1769 /// println!("This will never be printed!");
1774 /// let _x = HasDrop;
1775 /// process::abort();
1776 /// // the destructor implemented for HasDrop will never get run
1780 /// [panic hook]: crate::panic::set_hook
1781 #[stable(feature = "process_abort", since = "1.17.0")]
1782 pub fn abort() -> ! {
1783 crate::sys::abort_internal();
1786 /// Returns the OS-assigned process identifier associated with this process.
1793 /// use std::process;
1795 /// println!("My pid is {}", process::id());
1799 #[stable(feature = "getpid", since = "1.26.0")]
1800 pub fn id() -> u32 {
1801 crate::sys::os::getpid()
1804 /// A trait for implementing arbitrary return types in the `main` function.
1806 /// The C-main function only supports to return integers as return type.
1807 /// So, every type implementing the `Termination` trait has to be converted
1810 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1811 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1812 #[cfg_attr(not(test), lang = "termination")]
1813 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1814 #[rustc_on_unimplemented(
1815 message = "`main` has invalid return type `{Self}`",
1816 label = "`main` can only return types that implement `{Termination}`"
1818 pub trait Termination {
1819 /// Is called to get the representation of the value as status code.
1820 /// This status code is returned to the operating system.
1821 fn report(self) -> i32;
1824 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1825 impl Termination for () {
1827 fn report(self) -> i32 {
1828 ExitCode::SUCCESS.report()
1832 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1833 impl<E: fmt::Debug> Termination for Result<(), E> {
1834 fn report(self) -> i32 {
1836 Ok(()) => ().report(),
1837 Err(err) => Err::<!, _>(err).report(),
1842 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1843 impl Termination for ! {
1844 fn report(self) -> i32 {
1849 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1850 impl<E: fmt::Debug> Termination for Result<!, E> {
1851 fn report(self) -> i32 {
1852 let Err(err) = self;
1853 eprintln!("Error: {:?}", err);
1854 ExitCode::FAILURE.report()
1858 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1859 impl Termination for ExitCode {
1861 fn report(self) -> i32 {