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 passed to the program directly as is, so you shouldn't wrap it in quotes
561 /// or escape special characters the same way you would do that when running the program from terminal.
568 /// use std::process::Command;
570 /// Command::new("ls")
574 /// .expect("ls command failed to start");
576 #[stable(feature = "process", since = "1.0.0")]
577 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
578 self.inner.arg(arg.as_ref());
582 /// Adds multiple arguments to pass to the program.
584 /// To pass a single argument see [`arg`].
586 /// [`arg`]: Command::arg
588 /// Note that each argument is passed to the program directly as is, so you shouldn't wrap it in quotes
589 /// or escape special characters the same way you would do that when running the program from terminal directly.
596 /// use std::process::Command;
598 /// Command::new("ls")
599 /// .args(&["-l", "-a"])
601 /// .expect("ls command failed to start");
603 #[stable(feature = "process", since = "1.0.0")]
604 pub fn args<I, S>(&mut self, args: I) -> &mut Command
606 I: IntoIterator<Item = S>,
610 self.arg(arg.as_ref());
615 /// Inserts or updates an environment variable mapping.
617 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
618 /// and case-sensitive on all other platforms.
625 /// use std::process::Command;
627 /// Command::new("ls")
628 /// .env("PATH", "/bin")
630 /// .expect("ls command failed to start");
632 #[stable(feature = "process", since = "1.0.0")]
633 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
638 self.inner.env_mut().set(key.as_ref(), val.as_ref());
642 /// Adds or updates multiple environment variable mappings.
649 /// use std::process::{Command, Stdio};
651 /// use std::collections::HashMap;
653 /// let filtered_env : HashMap<String, String> =
654 /// env::vars().filter(|&(ref k, _)|
655 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
658 /// Command::new("printenv")
659 /// .stdin(Stdio::null())
660 /// .stdout(Stdio::inherit())
662 /// .envs(&filtered_env)
664 /// .expect("printenv failed to start");
666 #[stable(feature = "command_envs", since = "1.19.0")]
667 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
669 I: IntoIterator<Item = (K, V)>,
673 for (ref key, ref val) in vars {
674 self.inner.env_mut().set(key.as_ref(), val.as_ref());
679 /// Removes an environment variable mapping.
686 /// use std::process::Command;
688 /// Command::new("ls")
689 /// .env_remove("PATH")
691 /// .expect("ls command failed to start");
693 #[stable(feature = "process", since = "1.0.0")]
694 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
695 self.inner.env_mut().remove(key.as_ref());
699 /// Clears the entire environment map for the child process.
706 /// use std::process::Command;
708 /// Command::new("ls")
711 /// .expect("ls command failed to start");
713 #[stable(feature = "process", since = "1.0.0")]
714 pub fn env_clear(&mut self) -> &mut Command {
715 self.inner.env_mut().clear();
719 /// Sets the working directory for the child process.
721 /// # Platform-specific behavior
723 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
724 /// whether it should be interpreted relative to the parent's working
725 /// directory or relative to `current_dir`. The behavior in this case is
726 /// platform specific and unstable, and it's recommended to use
727 /// [`canonicalize`] to get an absolute program path instead.
734 /// use std::process::Command;
736 /// Command::new("ls")
737 /// .current_dir("/bin")
739 /// .expect("ls command failed to start");
742 /// [`canonicalize`]: crate::fs::canonicalize
743 #[stable(feature = "process", since = "1.0.0")]
744 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
745 self.inner.cwd(dir.as_ref().as_ref());
749 /// Configuration for the child process's standard input (stdin) handle.
751 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
752 /// defaults to [`piped`] when used with `output`.
754 /// [`inherit`]: Stdio::inherit
755 /// [`piped`]: Stdio::piped
762 /// use std::process::{Command, Stdio};
764 /// Command::new("ls")
765 /// .stdin(Stdio::null())
767 /// .expect("ls command failed to start");
769 #[stable(feature = "process", since = "1.0.0")]
770 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
771 self.inner.stdin(cfg.into().0);
775 /// Configuration for the child process's standard output (stdout) handle.
777 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
778 /// defaults to [`piped`] when used with `output`.
780 /// [`inherit`]: Stdio::inherit
781 /// [`piped`]: Stdio::piped
788 /// use std::process::{Command, Stdio};
790 /// Command::new("ls")
791 /// .stdout(Stdio::null())
793 /// .expect("ls command failed to start");
795 #[stable(feature = "process", since = "1.0.0")]
796 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
797 self.inner.stdout(cfg.into().0);
801 /// Configuration for the child process's standard error (stderr) handle.
803 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
804 /// defaults to [`piped`] when used with `output`.
806 /// [`inherit`]: Stdio::inherit
807 /// [`piped`]: Stdio::piped
814 /// use std::process::{Command, Stdio};
816 /// Command::new("ls")
817 /// .stderr(Stdio::null())
819 /// .expect("ls command failed to start");
821 #[stable(feature = "process", since = "1.0.0")]
822 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
823 self.inner.stderr(cfg.into().0);
827 /// Executes the command as a child process, returning a handle to it.
829 /// By default, stdin, stdout and stderr are inherited from the parent.
836 /// use std::process::Command;
838 /// Command::new("ls")
840 /// .expect("ls command failed to start");
842 #[stable(feature = "process", since = "1.0.0")]
843 pub fn spawn(&mut self) -> io::Result<Child> {
844 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
847 /// Executes the command as a child process, waiting for it to finish and
848 /// collecting all of its output.
850 /// By default, stdout and stderr are captured (and used to provide the
851 /// resulting output). Stdin is not inherited from the parent and any
852 /// attempt by the child process to read from the stdin stream will result
853 /// in the stream immediately closing.
858 /// use std::process::Command;
859 /// use std::io::{self, Write};
860 /// let output = Command::new("/bin/cat")
863 /// .expect("failed to execute process");
865 /// println!("status: {}", output.status);
866 /// io::stdout().write_all(&output.stdout).unwrap();
867 /// io::stderr().write_all(&output.stderr).unwrap();
869 /// assert!(output.status.success());
871 #[stable(feature = "process", since = "1.0.0")]
872 pub fn output(&mut self) -> io::Result<Output> {
874 .spawn(imp::Stdio::MakePipe, false)
875 .map(Child::from_inner)
876 .and_then(|p| p.wait_with_output())
879 /// Executes a command as a child process, waiting for it to finish and
880 /// collecting its exit status.
882 /// By default, stdin, stdout and stderr are inherited from the parent.
887 /// use std::process::Command;
889 /// let status = Command::new("/bin/cat")
892 /// .expect("failed to execute process");
894 /// println!("process exited with: {}", status);
896 /// assert!(status.success());
898 #[stable(feature = "process", since = "1.0.0")]
899 pub fn status(&mut self) -> io::Result<ExitStatus> {
901 .spawn(imp::Stdio::Inherit, true)
902 .map(Child::from_inner)
903 .and_then(|mut p| p.wait())
906 /// Returns the path to the program that was given to [`Command::new`].
911 /// # #![feature(command_access)]
912 /// use std::process::Command;
914 /// let cmd = Command::new("echo");
915 /// assert_eq!(cmd.get_program(), "echo");
917 #[unstable(feature = "command_access", issue = "44434")]
918 pub fn get_program(&self) -> &OsStr {
919 self.inner.get_program()
922 /// Returns an iterator of the arguments that will be passed to the program.
924 /// This does not include the path to the program as the first argument;
925 /// it only includes the arguments specified with [`Command::arg`] and
926 /// [`Command::args`].
931 /// # #![feature(command_access)]
932 /// use std::ffi::OsStr;
933 /// use std::process::Command;
935 /// let mut cmd = Command::new("echo");
936 /// cmd.arg("first").arg("second");
937 /// let args: Vec<&OsStr> = cmd.get_args().collect();
938 /// assert_eq!(args, &["first", "second"]);
940 #[unstable(feature = "command_access", issue = "44434")]
941 pub fn get_args(&self) -> CommandArgs<'_> {
942 CommandArgs { inner: self.inner.get_args() }
945 /// Returns an iterator of the environment variables that will be set when
946 /// the process is spawned.
948 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
949 /// value is the key, and the second is the value, which is [`None`] if
950 /// the environment variable is to be explicitly removed.
952 /// This only includes environment variables explicitly set with
953 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
954 /// does not include environment variables that will be inherited by the
960 /// # #![feature(command_access)]
961 /// use std::ffi::OsStr;
962 /// use std::process::Command;
964 /// let mut cmd = Command::new("ls");
965 /// cmd.env("TERM", "dumb").env_remove("TZ");
966 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
967 /// assert_eq!(envs, &[
968 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
969 /// (OsStr::new("TZ"), None)
972 #[unstable(feature = "command_access", issue = "44434")]
973 pub fn get_envs(&self) -> CommandEnvs<'_> {
974 self.inner.get_envs()
977 /// Returns the working directory for the child process.
979 /// This returns [`None`] if the working directory will not be changed.
984 /// # #![feature(command_access)]
985 /// use std::path::Path;
986 /// use std::process::Command;
988 /// let mut cmd = Command::new("ls");
989 /// assert_eq!(cmd.get_current_dir(), None);
990 /// cmd.current_dir("/bin");
991 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
993 #[unstable(feature = "command_access", issue = "44434")]
994 pub fn get_current_dir(&self) -> Option<&Path> {
995 self.inner.get_current_dir()
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl fmt::Debug for Command {
1001 /// Format the program and arguments of a Command for display. Any
1002 /// non-utf8 data is lossily converted using the utf8 replacement
1004 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009 impl AsInner<imp::Command> for Command {
1010 fn as_inner(&self) -> &imp::Command {
1015 impl AsInnerMut<imp::Command> for Command {
1016 fn as_inner_mut(&mut self) -> &mut imp::Command {
1021 /// An iterator over the command arguments.
1023 /// This struct is created by [`Command::get_args`]. See its documentation for
1025 #[unstable(feature = "command_access", issue = "44434")]
1027 pub struct CommandArgs<'a> {
1028 inner: imp::CommandArgs<'a>,
1031 #[unstable(feature = "command_access", issue = "44434")]
1032 impl<'a> Iterator for CommandArgs<'a> {
1033 type Item = &'a OsStr;
1034 fn next(&mut self) -> Option<&'a OsStr> {
1037 fn size_hint(&self) -> (usize, Option<usize>) {
1038 self.inner.size_hint()
1042 #[unstable(feature = "command_access", issue = "44434")]
1043 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1044 fn len(&self) -> usize {
1047 fn is_empty(&self) -> bool {
1048 self.inner.is_empty()
1052 /// The output of a finished process.
1054 /// This is returned in a Result by either the [`output`] method of a
1055 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1058 /// [`output`]: Command::output
1059 /// [`wait_with_output`]: Child::wait_with_output
1060 #[derive(PartialEq, Eq, Clone)]
1061 #[stable(feature = "process", since = "1.0.0")]
1063 /// The status (exit code) of the process.
1064 #[stable(feature = "process", since = "1.0.0")]
1065 pub status: ExitStatus,
1066 /// The data that the process wrote to stdout.
1067 #[stable(feature = "process", since = "1.0.0")]
1068 pub stdout: Vec<u8>,
1069 /// The data that the process wrote to stderr.
1070 #[stable(feature = "process", since = "1.0.0")]
1071 pub stderr: Vec<u8>,
1074 // If either stderr or stdout are valid utf8 strings it prints the valid
1075 // strings, otherwise it prints the byte sequence instead
1076 #[stable(feature = "process_output_debug", since = "1.7.0")]
1077 impl fmt::Debug for Output {
1078 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1079 let stdout_utf8 = str::from_utf8(&self.stdout);
1080 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1082 Err(_) => &self.stdout,
1085 let stderr_utf8 = str::from_utf8(&self.stderr);
1086 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1088 Err(_) => &self.stderr,
1091 fmt.debug_struct("Output")
1092 .field("status", &self.status)
1093 .field("stdout", stdout_debug)
1094 .field("stderr", stderr_debug)
1099 /// Describes what to do with a standard I/O stream for a child process when
1100 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1102 /// [`stdin`]: Command::stdin
1103 /// [`stdout`]: Command::stdout
1104 /// [`stderr`]: Command::stderr
1105 #[stable(feature = "process", since = "1.0.0")]
1106 pub struct Stdio(imp::Stdio);
1109 /// A new pipe should be arranged to connect the parent and child processes.
1116 /// use std::process::{Command, Stdio};
1118 /// let output = Command::new("echo")
1119 /// .arg("Hello, world!")
1120 /// .stdout(Stdio::piped())
1122 /// .expect("Failed to execute command");
1124 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1125 /// // Nothing echoed to console
1131 /// use std::io::Write;
1132 /// use std::process::{Command, Stdio};
1134 /// let mut child = Command::new("rev")
1135 /// .stdin(Stdio::piped())
1136 /// .stdout(Stdio::piped())
1138 /// .expect("Failed to spawn child process");
1141 /// let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1142 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1145 /// let output = child.wait_with_output().expect("Failed to read stdout");
1146 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1148 #[stable(feature = "process", since = "1.0.0")]
1149 pub fn piped() -> Stdio {
1150 Stdio(imp::Stdio::MakePipe)
1153 /// The child inherits from the corresponding parent descriptor.
1160 /// use std::process::{Command, Stdio};
1162 /// let output = Command::new("echo")
1163 /// .arg("Hello, world!")
1164 /// .stdout(Stdio::inherit())
1166 /// .expect("Failed to execute command");
1168 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1169 /// // "Hello, world!" echoed to console
1175 /// use std::process::{Command, Stdio};
1176 /// use std::io::{self, Write};
1178 /// let output = Command::new("rev")
1179 /// .stdin(Stdio::inherit())
1180 /// .stdout(Stdio::piped())
1182 /// .expect("Failed to execute command");
1184 /// print!("You piped in the reverse of: ");
1185 /// io::stdout().write_all(&output.stdout).unwrap();
1187 #[stable(feature = "process", since = "1.0.0")]
1188 pub fn inherit() -> Stdio {
1189 Stdio(imp::Stdio::Inherit)
1192 /// This stream will be ignored. This is the equivalent of attaching the
1193 /// stream to `/dev/null`.
1200 /// use std::process::{Command, Stdio};
1202 /// let output = Command::new("echo")
1203 /// .arg("Hello, world!")
1204 /// .stdout(Stdio::null())
1206 /// .expect("Failed to execute command");
1208 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1209 /// // Nothing echoed to console
1215 /// use std::process::{Command, Stdio};
1217 /// let output = Command::new("rev")
1218 /// .stdin(Stdio::null())
1219 /// .stdout(Stdio::piped())
1221 /// .expect("Failed to execute command");
1223 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1224 /// // Ignores any piped-in input
1226 #[stable(feature = "process", since = "1.0.0")]
1227 pub fn null() -> Stdio {
1228 Stdio(imp::Stdio::Null)
1232 impl FromInner<imp::Stdio> for Stdio {
1233 fn from_inner(inner: imp::Stdio) -> Stdio {
1238 #[stable(feature = "std_debug", since = "1.16.0")]
1239 impl fmt::Debug for Stdio {
1240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1241 f.pad("Stdio { .. }")
1245 #[stable(feature = "stdio_from", since = "1.20.0")]
1246 impl From<ChildStdin> for Stdio {
1247 /// Converts a `ChildStdin` into a `Stdio`
1251 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1254 /// use std::process::{Command, Stdio};
1256 /// let reverse = Command::new("rev")
1257 /// .stdin(Stdio::piped())
1259 /// .expect("failed reverse command");
1261 /// let _echo = Command::new("echo")
1262 /// .arg("Hello, world!")
1263 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1265 /// .expect("failed echo command");
1267 /// // "!dlrow ,olleH" echoed to console
1269 fn from(child: ChildStdin) -> Stdio {
1270 Stdio::from_inner(child.into_inner().into())
1274 #[stable(feature = "stdio_from", since = "1.20.0")]
1275 impl From<ChildStdout> for Stdio {
1276 /// Converts a `ChildStdout` into a `Stdio`
1280 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1283 /// use std::process::{Command, Stdio};
1285 /// let hello = Command::new("echo")
1286 /// .arg("Hello, world!")
1287 /// .stdout(Stdio::piped())
1289 /// .expect("failed echo command");
1291 /// let reverse = Command::new("rev")
1292 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1294 /// .expect("failed reverse command");
1296 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1298 fn from(child: ChildStdout) -> Stdio {
1299 Stdio::from_inner(child.into_inner().into())
1303 #[stable(feature = "stdio_from", since = "1.20.0")]
1304 impl From<ChildStderr> for Stdio {
1305 /// Converts a `ChildStderr` into a `Stdio`
1310 /// use std::process::{Command, Stdio};
1312 /// let reverse = Command::new("rev")
1313 /// .arg("non_existing_file.txt")
1314 /// .stderr(Stdio::piped())
1316 /// .expect("failed reverse command");
1318 /// let cat = Command::new("cat")
1320 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1322 /// .expect("failed echo command");
1325 /// String::from_utf8_lossy(&cat.stdout),
1326 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1329 fn from(child: ChildStderr) -> Stdio {
1330 Stdio::from_inner(child.into_inner().into())
1334 #[stable(feature = "stdio_from", since = "1.20.0")]
1335 impl From<fs::File> for Stdio {
1336 /// Converts a `File` into a `Stdio`
1340 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1343 /// use std::fs::File;
1344 /// use std::process::Command;
1346 /// // With the `foo.txt` file containing `Hello, world!"
1347 /// let file = File::open("foo.txt").unwrap();
1349 /// let reverse = Command::new("rev")
1350 /// .stdin(file) // Implicit File conversion into a Stdio
1352 /// .expect("failed reverse command");
1354 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1356 fn from(file: fs::File) -> Stdio {
1357 Stdio::from_inner(file.into_inner().into())
1361 /// Describes the result of a process after it has terminated.
1363 /// This `struct` is used to represent the exit status of a child process.
1364 /// Child processes are created via the [`Command`] struct and their exit
1365 /// status is exposed through the [`status`] method, or the [`wait`] method
1366 /// of a [`Child`] process.
1368 /// [`status`]: Command::status
1369 /// [`wait`]: Child::wait
1370 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1371 #[stable(feature = "process", since = "1.0.0")]
1372 pub struct ExitStatus(imp::ExitStatus);
1375 /// Was termination successful? Signal termination is not considered a
1376 /// success, and success is defined as a zero exit status.
1381 /// use std::process::Command;
1383 /// let status = Command::new("mkdir")
1384 /// .arg("projects")
1386 /// .expect("failed to execute mkdir");
1388 /// if status.success() {
1389 /// println!("'projects/' directory created");
1391 /// println!("failed to create 'projects/' directory");
1394 #[stable(feature = "process", since = "1.0.0")]
1395 pub fn success(&self) -> bool {
1399 /// Returns the exit code of the process, if any.
1401 /// On Unix, this will return `None` if the process was terminated
1402 /// by a signal; `std::os::unix` provides an extension trait for
1403 /// extracting the signal and other details from the `ExitStatus`.
1408 /// use std::process::Command;
1410 /// let status = Command::new("mkdir")
1411 /// .arg("projects")
1413 /// .expect("failed to execute mkdir");
1415 /// match status.code() {
1416 /// Some(code) => println!("Exited with status code: {}", code),
1417 /// None => println!("Process terminated by signal")
1420 #[stable(feature = "process", since = "1.0.0")]
1421 pub fn code(&self) -> Option<i32> {
1426 impl AsInner<imp::ExitStatus> for ExitStatus {
1427 fn as_inner(&self) -> &imp::ExitStatus {
1432 impl FromInner<imp::ExitStatus> for ExitStatus {
1433 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1438 #[stable(feature = "process", since = "1.0.0")]
1439 impl fmt::Display for ExitStatus {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1445 /// This type represents the status code a process can return to its
1446 /// parent under normal termination.
1448 /// Numeric values used in this type don't have portable meanings, and
1449 /// different platforms may mask different amounts of them.
1451 /// For the platform's canonical successful and unsuccessful codes, see
1452 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1454 /// [`SUCCESS`]: ExitCode::SUCCESS
1455 /// [`FAILURE`]: ExitCode::FAILURE
1457 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1458 /// it was ultimately cut from that RFC, and thus this type is more subject
1459 /// to change even than the usual unstable item churn.
1461 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1462 #[derive(Clone, Copy, Debug)]
1463 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1464 pub struct ExitCode(imp::ExitCode);
1466 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1468 /// The canonical ExitCode for successful termination on this platform.
1470 /// Note that a `()`-returning `main` implicitly results in a successful
1471 /// termination, so there's no need to return this from `main` unless
1472 /// you're also returning other possible codes.
1473 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1474 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1476 /// The canonical ExitCode for unsuccessful termination on this platform.
1478 /// If you're only returning this and `SUCCESS` from `main`, consider
1479 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1480 /// return the same codes (but will also `eprintln!` the error).
1481 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1482 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1486 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1487 /// error is returned.
1489 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1490 /// especially the [`Other`] kind might change to more specific kinds in the future.
1492 /// This is equivalent to sending a SIGKILL on Unix platforms.
1499 /// use std::process::Command;
1501 /// let mut command = Command::new("yes");
1502 /// if let Ok(mut child) = command.spawn() {
1503 /// child.kill().expect("command wasn't running");
1505 /// println!("yes command didn't start");
1509 /// [`ErrorKind`]: io::ErrorKind
1510 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1511 /// [`Other`]: io::ErrorKind::Other
1512 #[stable(feature = "process", since = "1.0.0")]
1513 pub fn kill(&mut self) -> io::Result<()> {
1517 /// Returns the OS-assigned process identifier associated with this child.
1524 /// use std::process::Command;
1526 /// let mut command = Command::new("ls");
1527 /// if let Ok(child) = command.spawn() {
1528 /// println!("Child's ID is {}", child.id());
1530 /// println!("ls command didn't start");
1533 #[stable(feature = "process_id", since = "1.3.0")]
1534 pub fn id(&self) -> u32 {
1538 /// Waits for the child to exit completely, returning the status that it
1539 /// exited with. This function will continue to have the same return value
1540 /// after it has been called at least once.
1542 /// The stdin handle to the child process, if any, will be closed
1543 /// before waiting. This helps avoid deadlock: it ensures that the
1544 /// child does not block waiting for input from the parent, while
1545 /// the parent waits for the child to exit.
1552 /// use std::process::Command;
1554 /// let mut command = Command::new("ls");
1555 /// if let Ok(mut child) = command.spawn() {
1556 /// child.wait().expect("command wasn't running");
1557 /// println!("Child has finished its execution!");
1559 /// println!("ls command didn't start");
1562 #[stable(feature = "process", since = "1.0.0")]
1563 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1564 drop(self.stdin.take());
1565 self.handle.wait().map(ExitStatus)
1568 /// Attempts to collect the exit status of the child if it has already
1571 /// This function will not block the calling thread and will only
1572 /// check to see if the child process has exited or not. If the child has
1573 /// exited then on Unix the process ID is reaped. This function is
1574 /// guaranteed to repeatedly return a successful exit status so long as the
1575 /// child has already exited.
1577 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1578 /// exit status is not available at this time then `Ok(None)` is returned.
1579 /// If an error occurs, then that error is returned.
1581 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1588 /// use std::process::Command;
1590 /// let mut child = Command::new("ls").spawn().unwrap();
1592 /// match child.try_wait() {
1593 /// Ok(Some(status)) => println!("exited with: {}", status),
1595 /// println!("status not ready yet, let's really wait");
1596 /// let res = child.wait();
1597 /// println!("result: {:?}", res);
1599 /// Err(e) => println!("error attempting to wait: {}", e),
1602 #[stable(feature = "process_try_wait", since = "1.18.0")]
1603 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1604 Ok(self.handle.try_wait()?.map(ExitStatus))
1607 /// Simultaneously waits for the child to exit and collect all remaining
1608 /// output on the stdout/stderr handles, returning an `Output`
1611 /// The stdin handle to the child process, if any, will be closed
1612 /// before waiting. This helps avoid deadlock: it ensures that the
1613 /// child does not block waiting for input from the parent, while
1614 /// the parent waits for the child to exit.
1616 /// By default, stdin, stdout and stderr are inherited from the parent.
1617 /// In order to capture the output into this `Result<Output>` it is
1618 /// necessary to create new pipes between parent and child. Use
1619 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1624 /// use std::process::{Command, Stdio};
1626 /// let child = Command::new("/bin/cat")
1627 /// .arg("file.txt")
1628 /// .stdout(Stdio::piped())
1630 /// .expect("failed to execute child");
1632 /// let output = child
1633 /// .wait_with_output()
1634 /// .expect("failed to wait on child");
1636 /// assert!(output.status.success());
1639 #[stable(feature = "process", since = "1.0.0")]
1640 pub fn wait_with_output(mut self) -> io::Result<Output> {
1641 drop(self.stdin.take());
1643 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1644 match (self.stdout.take(), self.stderr.take()) {
1646 (Some(mut out), None) => {
1647 let res = out.read_to_end(&mut stdout);
1650 (None, Some(mut err)) => {
1651 let res = err.read_to_end(&mut stderr);
1654 (Some(out), Some(err)) => {
1655 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1660 let status = self.wait()?;
1661 Ok(Output { status, stdout, stderr })
1665 /// Terminates the current process with the specified exit code.
1667 /// This function will never return and will immediately terminate the current
1668 /// process. The exit code is passed through to the underlying OS and will be
1669 /// available for consumption by another process.
1671 /// Note that because this function never returns, and that it terminates the
1672 /// process, no destructors on the current stack or any other thread's stack
1673 /// will be run. If a clean shutdown is needed it is recommended to only call
1674 /// this function at a known point where there are no more destructors left
1677 /// ## Platform-specific behavior
1679 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1680 /// will be visible to a parent process inspecting the exit code. On most
1681 /// Unix-like platforms, only the eight least-significant bits are considered.
1685 /// Due to this function’s behavior regarding destructors, a conventional way
1686 /// to use the function is to extract the actual computation to another
1687 /// function and compute the exit code from its return value:
1690 /// fn run_app() -> Result<(), ()> {
1691 /// // Application logic here
1696 /// std::process::exit(match run_app() {
1699 /// eprintln!("error: {:?}", err);
1706 /// Due to [platform-specific behavior], the exit code for this example will be
1707 /// `0` on Linux, but `256` on Windows:
1710 /// use std::process;
1712 /// process::exit(0x0100);
1715 /// [platform-specific behavior]: #platform-specific-behavior
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 pub fn exit(code: i32) -> ! {
1718 crate::sys_common::cleanup();
1719 crate::sys::os::exit(code)
1722 /// Terminates the process in an abnormal fashion.
1724 /// The function will never return and will immediately terminate the current
1725 /// process in a platform specific "abnormal" manner.
1727 /// Note that because this function never returns, and that it terminates the
1728 /// process, no destructors on the current stack or any other thread's stack
1731 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1732 /// the current thread's stack and calls all destructors.
1733 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1734 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1735 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1737 /// If a clean shutdown is needed it is recommended to only call
1738 /// this function at a known point where there are no more destructors left
1744 /// use std::process;
1747 /// println!("aborting");
1749 /// process::abort();
1751 /// // execution never gets here
1755 /// The `abort` function terminates the process, so the destructor will not
1756 /// get run on the example below:
1759 /// use std::process;
1763 /// impl Drop for HasDrop {
1764 /// fn drop(&mut self) {
1765 /// println!("This will never be printed!");
1770 /// let _x = HasDrop;
1771 /// process::abort();
1772 /// // the destructor implemented for HasDrop will never get run
1776 /// [panic hook]: crate::panic::set_hook
1777 #[stable(feature = "process_abort", since = "1.17.0")]
1778 pub fn abort() -> ! {
1779 crate::sys::abort_internal();
1782 /// Returns the OS-assigned process identifier associated with this process.
1789 /// use std::process;
1791 /// println!("My pid is {}", process::id());
1795 #[stable(feature = "getpid", since = "1.26.0")]
1796 pub fn id() -> u32 {
1797 crate::sys::os::getpid()
1800 /// A trait for implementing arbitrary return types in the `main` function.
1802 /// The C-main function only supports to return integers as return type.
1803 /// So, every type implementing the `Termination` trait has to be converted
1806 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1807 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1808 #[cfg_attr(not(test), lang = "termination")]
1809 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1810 #[rustc_on_unimplemented(
1811 message = "`main` has invalid return type `{Self}`",
1812 label = "`main` can only return types that implement `{Termination}`"
1814 pub trait Termination {
1815 /// Is called to get the representation of the value as status code.
1816 /// This status code is returned to the operating system.
1817 fn report(self) -> i32;
1820 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1821 impl Termination for () {
1823 fn report(self) -> i32 {
1824 ExitCode::SUCCESS.report()
1828 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1829 impl<E: fmt::Debug> Termination for Result<(), E> {
1830 fn report(self) -> i32 {
1832 Ok(()) => ().report(),
1833 Err(err) => Err::<!, _>(err).report(),
1838 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1839 impl Termination for ! {
1840 fn report(self) -> i32 {
1845 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1846 impl<E: fmt::Debug> Termination for Result<!, E> {
1847 fn report(self) -> i32 {
1848 let Err(err) = self;
1849 eprintln!("Error: {:?}", err);
1850 ExitCode::FAILURE.report()
1854 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1855 impl Termination for ExitCode {
1857 fn report(self) -> i32 {