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
565 /// use std::process::Command;
567 /// Command::new("ls")
571 /// .expect("ls command failed to start");
573 #[stable(feature = "process", since = "1.0.0")]
574 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
575 self.inner.arg(arg.as_ref());
579 /// Adds multiple arguments to pass to the program.
581 /// To pass a single argument see [`arg`].
583 /// [`arg`]: Command::arg
590 /// use std::process::Command;
592 /// Command::new("ls")
593 /// .args(&["-l", "-a"])
595 /// .expect("ls command failed to start");
597 #[stable(feature = "process", since = "1.0.0")]
598 pub fn args<I, S>(&mut self, args: I) -> &mut Command
600 I: IntoIterator<Item = S>,
604 self.arg(arg.as_ref());
609 /// Inserts or updates an environment variable mapping.
611 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
612 /// and case-sensitive on all other platforms.
619 /// use std::process::Command;
621 /// Command::new("ls")
622 /// .env("PATH", "/bin")
624 /// .expect("ls command failed to start");
626 #[stable(feature = "process", since = "1.0.0")]
627 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
632 self.inner.env_mut().set(key.as_ref(), val.as_ref());
636 /// Adds or updates multiple environment variable mappings.
643 /// use std::process::{Command, Stdio};
645 /// use std::collections::HashMap;
647 /// let filtered_env : HashMap<String, String> =
648 /// env::vars().filter(|&(ref k, _)|
649 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
652 /// Command::new("printenv")
653 /// .stdin(Stdio::null())
654 /// .stdout(Stdio::inherit())
656 /// .envs(&filtered_env)
658 /// .expect("printenv failed to start");
660 #[stable(feature = "command_envs", since = "1.19.0")]
661 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
663 I: IntoIterator<Item = (K, V)>,
667 for (ref key, ref val) in vars {
668 self.inner.env_mut().set(key.as_ref(), val.as_ref());
673 /// Removes an environment variable mapping.
680 /// use std::process::Command;
682 /// Command::new("ls")
683 /// .env_remove("PATH")
685 /// .expect("ls command failed to start");
687 #[stable(feature = "process", since = "1.0.0")]
688 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
689 self.inner.env_mut().remove(key.as_ref());
693 /// Clears the entire environment map for the child process.
700 /// use std::process::Command;
702 /// Command::new("ls")
705 /// .expect("ls command failed to start");
707 #[stable(feature = "process", since = "1.0.0")]
708 pub fn env_clear(&mut self) -> &mut Command {
709 self.inner.env_mut().clear();
713 /// Sets the working directory for the child process.
715 /// # Platform-specific behavior
717 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
718 /// whether it should be interpreted relative to the parent's working
719 /// directory or relative to `current_dir`. The behavior in this case is
720 /// platform specific and unstable, and it's recommended to use
721 /// [`canonicalize`] to get an absolute program path instead.
728 /// use std::process::Command;
730 /// Command::new("ls")
731 /// .current_dir("/bin")
733 /// .expect("ls command failed to start");
736 /// [`canonicalize`]: crate::fs::canonicalize
737 #[stable(feature = "process", since = "1.0.0")]
738 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
739 self.inner.cwd(dir.as_ref().as_ref());
743 /// Configuration for the child process's standard input (stdin) handle.
745 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
746 /// defaults to [`piped`] when used with `output`.
748 /// [`inherit`]: Stdio::inherit
749 /// [`piped`]: Stdio::piped
756 /// use std::process::{Command, Stdio};
758 /// Command::new("ls")
759 /// .stdin(Stdio::null())
761 /// .expect("ls command failed to start");
763 #[stable(feature = "process", since = "1.0.0")]
764 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
765 self.inner.stdin(cfg.into().0);
769 /// Configuration for the child process's standard output (stdout) handle.
771 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
772 /// defaults to [`piped`] when used with `output`.
774 /// [`inherit`]: Stdio::inherit
775 /// [`piped`]: Stdio::piped
782 /// use std::process::{Command, Stdio};
784 /// Command::new("ls")
785 /// .stdout(Stdio::null())
787 /// .expect("ls command failed to start");
789 #[stable(feature = "process", since = "1.0.0")]
790 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
791 self.inner.stdout(cfg.into().0);
795 /// Configuration for the child process's standard error (stderr) handle.
797 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
798 /// defaults to [`piped`] when used with `output`.
800 /// [`inherit`]: Stdio::inherit
801 /// [`piped`]: Stdio::piped
808 /// use std::process::{Command, Stdio};
810 /// Command::new("ls")
811 /// .stderr(Stdio::null())
813 /// .expect("ls command failed to start");
815 #[stable(feature = "process", since = "1.0.0")]
816 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
817 self.inner.stderr(cfg.into().0);
821 /// Executes the command as a child process, returning a handle to it.
823 /// By default, stdin, stdout and stderr are inherited from the parent.
830 /// use std::process::Command;
832 /// Command::new("ls")
834 /// .expect("ls command failed to start");
836 #[stable(feature = "process", since = "1.0.0")]
837 pub fn spawn(&mut self) -> io::Result<Child> {
838 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
841 /// Executes the command as a child process, waiting for it to finish and
842 /// collecting all of its output.
844 /// By default, stdout and stderr are captured (and used to provide the
845 /// resulting output). Stdin is not inherited from the parent and any
846 /// attempt by the child process to read from the stdin stream will result
847 /// in the stream immediately closing.
852 /// use std::process::Command;
853 /// use std::io::{self, Write};
854 /// let output = Command::new("/bin/cat")
857 /// .expect("failed to execute process");
859 /// println!("status: {}", output.status);
860 /// io::stdout().write_all(&output.stdout).unwrap();
861 /// io::stderr().write_all(&output.stderr).unwrap();
863 /// assert!(output.status.success());
865 #[stable(feature = "process", since = "1.0.0")]
866 pub fn output(&mut self) -> io::Result<Output> {
868 .spawn(imp::Stdio::MakePipe, false)
869 .map(Child::from_inner)
870 .and_then(|p| p.wait_with_output())
873 /// Executes a command as a child process, waiting for it to finish and
874 /// collecting its exit status.
876 /// By default, stdin, stdout and stderr are inherited from the parent.
881 /// use std::process::Command;
883 /// let status = Command::new("/bin/cat")
886 /// .expect("failed to execute process");
888 /// println!("process exited with: {}", status);
890 /// assert!(status.success());
892 #[stable(feature = "process", since = "1.0.0")]
893 pub fn status(&mut self) -> io::Result<ExitStatus> {
895 .spawn(imp::Stdio::Inherit, true)
896 .map(Child::from_inner)
897 .and_then(|mut p| p.wait())
900 /// Returns the path to the program that was given to [`Command::new`].
905 /// # #![feature(command_access)]
906 /// use std::process::Command;
908 /// let cmd = Command::new("echo");
909 /// assert_eq!(cmd.get_program(), "echo");
911 #[unstable(feature = "command_access", issue = "44434")]
912 pub fn get_program(&self) -> &OsStr {
913 self.inner.get_program()
916 /// Returns an iterator of the arguments that will be passed to the program.
918 /// This does not include the path to the program as the first argument;
919 /// it only includes the arguments specified with [`Command::arg`] and
920 /// [`Command::args`].
925 /// # #![feature(command_access)]
926 /// use std::ffi::OsStr;
927 /// use std::process::Command;
929 /// let mut cmd = Command::new("echo");
930 /// cmd.arg("first").arg("second");
931 /// let args: Vec<&OsStr> = cmd.get_args().collect();
932 /// assert_eq!(args, &["first", "second"]);
934 #[unstable(feature = "command_access", issue = "44434")]
935 pub fn get_args(&self) -> CommandArgs<'_> {
936 CommandArgs { inner: self.inner.get_args() }
939 /// Returns an iterator of the environment variables that will be set when
940 /// the process is spawned.
942 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
943 /// value is the key, and the second is the value, which is [`None`] if
944 /// the environment variable is to be explicitly removed.
946 /// This only includes environment variables explicitly set with
947 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
948 /// does not include environment variables that will be inherited by the
954 /// # #![feature(command_access)]
955 /// use std::ffi::OsStr;
956 /// use std::process::Command;
958 /// let mut cmd = Command::new("ls");
959 /// cmd.env("TERM", "dumb").env_remove("TZ");
960 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
961 /// assert_eq!(envs, &[
962 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
963 /// (OsStr::new("TZ"), None)
966 #[unstable(feature = "command_access", issue = "44434")]
967 pub fn get_envs(&self) -> CommandEnvs<'_> {
968 self.inner.get_envs()
971 /// Returns the working directory for the child process.
973 /// This returns [`None`] if the working directory will not be changed.
978 /// # #![feature(command_access)]
979 /// use std::path::Path;
980 /// use std::process::Command;
982 /// let mut cmd = Command::new("ls");
983 /// assert_eq!(cmd.get_current_dir(), None);
984 /// cmd.current_dir("/bin");
985 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
987 #[unstable(feature = "command_access", issue = "44434")]
988 pub fn get_current_dir(&self) -> Option<&Path> {
989 self.inner.get_current_dir()
993 #[stable(feature = "rust1", since = "1.0.0")]
994 impl fmt::Debug for Command {
995 /// Format the program and arguments of a Command for display. Any
996 /// non-utf8 data is lossily converted using the utf8 replacement
998 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1003 impl AsInner<imp::Command> for Command {
1004 fn as_inner(&self) -> &imp::Command {
1009 impl AsInnerMut<imp::Command> for Command {
1010 fn as_inner_mut(&mut self) -> &mut imp::Command {
1015 /// An iterator over the command arguments.
1017 /// This struct is created by [`Command::get_args`]. See its documentation for
1019 #[unstable(feature = "command_access", issue = "44434")]
1021 pub struct CommandArgs<'a> {
1022 inner: imp::CommandArgs<'a>,
1025 #[unstable(feature = "command_access", issue = "44434")]
1026 impl<'a> Iterator for CommandArgs<'a> {
1027 type Item = &'a OsStr;
1028 fn next(&mut self) -> Option<&'a OsStr> {
1031 fn size_hint(&self) -> (usize, Option<usize>) {
1032 self.inner.size_hint()
1036 #[unstable(feature = "command_access", issue = "44434")]
1037 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1038 fn len(&self) -> usize {
1041 fn is_empty(&self) -> bool {
1042 self.inner.is_empty()
1046 /// The output of a finished process.
1048 /// This is returned in a Result by either the [`output`] method of a
1049 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1052 /// [`output`]: Command::output
1053 /// [`wait_with_output`]: Child::wait_with_output
1054 #[derive(PartialEq, Eq, Clone)]
1055 #[stable(feature = "process", since = "1.0.0")]
1057 /// The status (exit code) of the process.
1058 #[stable(feature = "process", since = "1.0.0")]
1059 pub status: ExitStatus,
1060 /// The data that the process wrote to stdout.
1061 #[stable(feature = "process", since = "1.0.0")]
1062 pub stdout: Vec<u8>,
1063 /// The data that the process wrote to stderr.
1064 #[stable(feature = "process", since = "1.0.0")]
1065 pub stderr: Vec<u8>,
1068 // If either stderr or stdout are valid utf8 strings it prints the valid
1069 // strings, otherwise it prints the byte sequence instead
1070 #[stable(feature = "process_output_debug", since = "1.7.0")]
1071 impl fmt::Debug for Output {
1072 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1073 let stdout_utf8 = str::from_utf8(&self.stdout);
1074 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1076 Err(_) => &self.stdout,
1079 let stderr_utf8 = str::from_utf8(&self.stderr);
1080 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1082 Err(_) => &self.stderr,
1085 fmt.debug_struct("Output")
1086 .field("status", &self.status)
1087 .field("stdout", stdout_debug)
1088 .field("stderr", stderr_debug)
1093 /// Describes what to do with a standard I/O stream for a child process when
1094 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1096 /// [`stdin`]: Command::stdin
1097 /// [`stdout`]: Command::stdout
1098 /// [`stderr`]: Command::stderr
1099 #[stable(feature = "process", since = "1.0.0")]
1100 pub struct Stdio(imp::Stdio);
1103 /// A new pipe should be arranged to connect the parent and child processes.
1110 /// use std::process::{Command, Stdio};
1112 /// let output = Command::new("echo")
1113 /// .arg("Hello, world!")
1114 /// .stdout(Stdio::piped())
1116 /// .expect("Failed to execute command");
1118 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1119 /// // Nothing echoed to console
1125 /// use std::io::Write;
1126 /// use std::process::{Command, Stdio};
1128 /// let mut child = Command::new("rev")
1129 /// .stdin(Stdio::piped())
1130 /// .stdout(Stdio::piped())
1132 /// .expect("Failed to spawn child process");
1135 /// let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1136 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1139 /// let output = child.wait_with_output().expect("Failed to read stdout");
1140 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1142 #[stable(feature = "process", since = "1.0.0")]
1143 pub fn piped() -> Stdio {
1144 Stdio(imp::Stdio::MakePipe)
1147 /// The child inherits from the corresponding parent descriptor.
1154 /// use std::process::{Command, Stdio};
1156 /// let output = Command::new("echo")
1157 /// .arg("Hello, world!")
1158 /// .stdout(Stdio::inherit())
1160 /// .expect("Failed to execute command");
1162 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1163 /// // "Hello, world!" echoed to console
1169 /// use std::process::{Command, Stdio};
1170 /// use std::io::{self, Write};
1172 /// let output = Command::new("rev")
1173 /// .stdin(Stdio::inherit())
1174 /// .stdout(Stdio::piped())
1176 /// .expect("Failed to execute command");
1178 /// print!("You piped in the reverse of: ");
1179 /// io::stdout().write_all(&output.stdout).unwrap();
1181 #[stable(feature = "process", since = "1.0.0")]
1182 pub fn inherit() -> Stdio {
1183 Stdio(imp::Stdio::Inherit)
1186 /// This stream will be ignored. This is the equivalent of attaching the
1187 /// stream to `/dev/null`
1194 /// use std::process::{Command, Stdio};
1196 /// let output = Command::new("echo")
1197 /// .arg("Hello, world!")
1198 /// .stdout(Stdio::null())
1200 /// .expect("Failed to execute command");
1202 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1203 /// // Nothing echoed to console
1209 /// use std::process::{Command, Stdio};
1211 /// let output = Command::new("rev")
1212 /// .stdin(Stdio::null())
1213 /// .stdout(Stdio::piped())
1215 /// .expect("Failed to execute command");
1217 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1218 /// // Ignores any piped-in input
1220 #[stable(feature = "process", since = "1.0.0")]
1221 pub fn null() -> Stdio {
1222 Stdio(imp::Stdio::Null)
1226 impl FromInner<imp::Stdio> for Stdio {
1227 fn from_inner(inner: imp::Stdio) -> Stdio {
1232 #[stable(feature = "std_debug", since = "1.16.0")]
1233 impl fmt::Debug for Stdio {
1234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1235 f.pad("Stdio { .. }")
1239 #[stable(feature = "stdio_from", since = "1.20.0")]
1240 impl From<ChildStdin> for Stdio {
1241 /// Converts a `ChildStdin` into a `Stdio`
1245 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1248 /// use std::process::{Command, Stdio};
1250 /// let reverse = Command::new("rev")
1251 /// .stdin(Stdio::piped())
1253 /// .expect("failed reverse command");
1255 /// let _echo = Command::new("echo")
1256 /// .arg("Hello, world!")
1257 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1259 /// .expect("failed echo command");
1261 /// // "!dlrow ,olleH" echoed to console
1263 fn from(child: ChildStdin) -> Stdio {
1264 Stdio::from_inner(child.into_inner().into())
1268 #[stable(feature = "stdio_from", since = "1.20.0")]
1269 impl From<ChildStdout> for Stdio {
1270 /// Converts a `ChildStdout` into a `Stdio`
1274 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1277 /// use std::process::{Command, Stdio};
1279 /// let hello = Command::new("echo")
1280 /// .arg("Hello, world!")
1281 /// .stdout(Stdio::piped())
1283 /// .expect("failed echo command");
1285 /// let reverse = Command::new("rev")
1286 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1288 /// .expect("failed reverse command");
1290 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1292 fn from(child: ChildStdout) -> Stdio {
1293 Stdio::from_inner(child.into_inner().into())
1297 #[stable(feature = "stdio_from", since = "1.20.0")]
1298 impl From<ChildStderr> for Stdio {
1299 /// Converts a `ChildStderr` into a `Stdio`
1304 /// use std::process::{Command, Stdio};
1306 /// let reverse = Command::new("rev")
1307 /// .arg("non_existing_file.txt")
1308 /// .stderr(Stdio::piped())
1310 /// .expect("failed reverse command");
1312 /// let cat = Command::new("cat")
1314 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1316 /// .expect("failed echo command");
1319 /// String::from_utf8_lossy(&cat.stdout),
1320 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1323 fn from(child: ChildStderr) -> Stdio {
1324 Stdio::from_inner(child.into_inner().into())
1328 #[stable(feature = "stdio_from", since = "1.20.0")]
1329 impl From<fs::File> for Stdio {
1330 /// Converts a `File` into a `Stdio`
1334 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1337 /// use std::fs::File;
1338 /// use std::process::Command;
1340 /// // With the `foo.txt` file containing `Hello, world!"
1341 /// let file = File::open("foo.txt").unwrap();
1343 /// let reverse = Command::new("rev")
1344 /// .stdin(file) // Implicit File conversion into a Stdio
1346 /// .expect("failed reverse command");
1348 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1350 fn from(file: fs::File) -> Stdio {
1351 Stdio::from_inner(file.into_inner().into())
1355 /// Describes the result of a process after it has terminated.
1357 /// This `struct` is used to represent the exit status of a child process.
1358 /// Child processes are created via the [`Command`] struct and their exit
1359 /// status is exposed through the [`status`] method, or the [`wait`] method
1360 /// of a [`Child`] process.
1362 /// [`status`]: Command::status
1363 /// [`wait`]: Child::wait
1364 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1365 #[stable(feature = "process", since = "1.0.0")]
1366 pub struct ExitStatus(imp::ExitStatus);
1369 /// Was termination successful? Signal termination is not considered a
1370 /// success, and success is defined as a zero exit status.
1375 /// use std::process::Command;
1377 /// let status = Command::new("mkdir")
1378 /// .arg("projects")
1380 /// .expect("failed to execute mkdir");
1382 /// if status.success() {
1383 /// println!("'projects/' directory created");
1385 /// println!("failed to create 'projects/' directory");
1388 #[stable(feature = "process", since = "1.0.0")]
1389 pub fn success(&self) -> bool {
1393 /// Returns the exit code of the process, if any.
1395 /// On Unix, this will return `None` if the process was terminated
1396 /// by a signal; `std::os::unix` provides an extension trait for
1397 /// extracting the signal and other details from the `ExitStatus`.
1402 /// use std::process::Command;
1404 /// let status = Command::new("mkdir")
1405 /// .arg("projects")
1407 /// .expect("failed to execute mkdir");
1409 /// match status.code() {
1410 /// Some(code) => println!("Exited with status code: {}", code),
1411 /// None => println!("Process terminated by signal")
1414 #[stable(feature = "process", since = "1.0.0")]
1415 pub fn code(&self) -> Option<i32> {
1420 impl AsInner<imp::ExitStatus> for ExitStatus {
1421 fn as_inner(&self) -> &imp::ExitStatus {
1426 impl FromInner<imp::ExitStatus> for ExitStatus {
1427 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1432 #[stable(feature = "process", since = "1.0.0")]
1433 impl fmt::Display for ExitStatus {
1434 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439 /// This type represents the status code a process can return to its
1440 /// parent under normal termination.
1442 /// Numeric values used in this type don't have portable meanings, and
1443 /// different platforms may mask different amounts of them.
1445 /// For the platform's canonical successful and unsuccessful codes, see
1446 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1448 /// [`SUCCESS`]: ExitCode::SUCCESS
1449 /// [`FAILURE`]: ExitCode::FAILURE
1451 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1452 /// it was ultimately cut from that RFC, and thus this type is more subject
1453 /// to change even than the usual unstable item churn.
1455 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1456 #[derive(Clone, Copy, Debug)]
1457 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1458 pub struct ExitCode(imp::ExitCode);
1460 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1462 /// The canonical ExitCode for successful termination on this platform.
1464 /// Note that a `()`-returning `main` implicitly results in a successful
1465 /// termination, so there's no need to return this from `main` unless
1466 /// you're also returning other possible codes.
1467 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1468 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1470 /// The canonical ExitCode for unsuccessful termination on this platform.
1472 /// If you're only returning this and `SUCCESS` from `main`, consider
1473 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1474 /// return the same codes (but will also `eprintln!` the error).
1475 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1476 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1480 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1481 /// error is returned.
1483 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1484 /// especially the [`Other`] kind might change to more specific kinds in the future.
1486 /// This is equivalent to sending a SIGKILL on Unix platforms.
1493 /// use std::process::Command;
1495 /// let mut command = Command::new("yes");
1496 /// if let Ok(mut child) = command.spawn() {
1497 /// child.kill().expect("command wasn't running");
1499 /// println!("yes command didn't start");
1503 /// [`ErrorKind`]: io::ErrorKind
1504 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1505 /// [`Other`]: io::ErrorKind::Other
1506 #[stable(feature = "process", since = "1.0.0")]
1507 pub fn kill(&mut self) -> io::Result<()> {
1511 /// Returns the OS-assigned process identifier associated with this child.
1518 /// use std::process::Command;
1520 /// let mut command = Command::new("ls");
1521 /// if let Ok(child) = command.spawn() {
1522 /// println!("Child's ID is {}", child.id());
1524 /// println!("ls command didn't start");
1527 #[stable(feature = "process_id", since = "1.3.0")]
1528 pub fn id(&self) -> u32 {
1532 /// Waits for the child to exit completely, returning the status that it
1533 /// exited with. This function will continue to have the same return value
1534 /// after it has been called at least once.
1536 /// The stdin handle to the child process, if any, will be closed
1537 /// before waiting. This helps avoid deadlock: it ensures that the
1538 /// child does not block waiting for input from the parent, while
1539 /// the parent waits for the child to exit.
1546 /// use std::process::Command;
1548 /// let mut command = Command::new("ls");
1549 /// if let Ok(mut child) = command.spawn() {
1550 /// child.wait().expect("command wasn't running");
1551 /// println!("Child has finished its execution!");
1553 /// println!("ls command didn't start");
1556 #[stable(feature = "process", since = "1.0.0")]
1557 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1558 drop(self.stdin.take());
1559 self.handle.wait().map(ExitStatus)
1562 /// Attempts to collect the exit status of the child if it has already
1565 /// This function will not block the calling thread and will only
1566 /// check to see if the child process has exited or not. If the child has
1567 /// exited then on Unix the process ID is reaped. This function is
1568 /// guaranteed to repeatedly return a successful exit status so long as the
1569 /// child has already exited.
1571 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1572 /// exit status is not available at this time then `Ok(None)` is returned.
1573 /// If an error occurs, then that error is returned.
1575 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1582 /// use std::process::Command;
1584 /// let mut child = Command::new("ls").spawn().unwrap();
1586 /// match child.try_wait() {
1587 /// Ok(Some(status)) => println!("exited with: {}", status),
1589 /// println!("status not ready yet, let's really wait");
1590 /// let res = child.wait();
1591 /// println!("result: {:?}", res);
1593 /// Err(e) => println!("error attempting to wait: {}", e),
1596 #[stable(feature = "process_try_wait", since = "1.18.0")]
1597 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1598 Ok(self.handle.try_wait()?.map(ExitStatus))
1601 /// Simultaneously waits for the child to exit and collect all remaining
1602 /// output on the stdout/stderr handles, returning an `Output`
1605 /// The stdin handle to the child process, if any, will be closed
1606 /// before waiting. This helps avoid deadlock: it ensures that the
1607 /// child does not block waiting for input from the parent, while
1608 /// the parent waits for the child to exit.
1610 /// By default, stdin, stdout and stderr are inherited from the parent.
1611 /// In order to capture the output into this `Result<Output>` it is
1612 /// necessary to create new pipes between parent and child. Use
1613 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1618 /// use std::process::{Command, Stdio};
1620 /// let child = Command::new("/bin/cat")
1621 /// .arg("file.txt")
1622 /// .stdout(Stdio::piped())
1624 /// .expect("failed to execute child");
1626 /// let output = child
1627 /// .wait_with_output()
1628 /// .expect("failed to wait on child");
1630 /// assert!(output.status.success());
1633 #[stable(feature = "process", since = "1.0.0")]
1634 pub fn wait_with_output(mut self) -> io::Result<Output> {
1635 drop(self.stdin.take());
1637 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1638 match (self.stdout.take(), self.stderr.take()) {
1640 (Some(mut out), None) => {
1641 let res = out.read_to_end(&mut stdout);
1644 (None, Some(mut err)) => {
1645 let res = err.read_to_end(&mut stderr);
1648 (Some(out), Some(err)) => {
1649 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1654 let status = self.wait()?;
1655 Ok(Output { status, stdout, stderr })
1659 /// Terminates the current process with the specified exit code.
1661 /// This function will never return and will immediately terminate the current
1662 /// process. The exit code is passed through to the underlying OS and will be
1663 /// available for consumption by another process.
1665 /// Note that because this function never returns, and that it terminates the
1666 /// process, no destructors on the current stack or any other thread's stack
1667 /// will be run. If a clean shutdown is needed it is recommended to only call
1668 /// this function at a known point where there are no more destructors left
1671 /// ## Platform-specific behavior
1673 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1674 /// will be visible to a parent process inspecting the exit code. On most
1675 /// Unix-like platforms, only the eight least-significant bits are considered.
1679 /// Due to this function’s behavior regarding destructors, a conventional way
1680 /// to use the function is to extract the actual computation to another
1681 /// function and compute the exit code from its return value:
1684 /// fn run_app() -> Result<(), ()> {
1685 /// // Application logic here
1690 /// std::process::exit(match run_app() {
1693 /// eprintln!("error: {:?}", err);
1700 /// Due to [platform-specific behavior], the exit code for this example will be
1701 /// `0` on Linux, but `256` on Windows:
1704 /// use std::process;
1706 /// process::exit(0x0100);
1709 /// [platform-specific behavior]: #platform-specific-behavior
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 pub fn exit(code: i32) -> ! {
1712 crate::sys_common::cleanup();
1713 crate::sys::os::exit(code)
1716 /// Terminates the process in an abnormal fashion.
1718 /// The function will never return and will immediately terminate the current
1719 /// process in a platform specific "abnormal" manner.
1721 /// Note that because this function never returns, and that it terminates the
1722 /// process, no destructors on the current stack or any other thread's stack
1725 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1726 /// the current thread's stack and calls all destructors.
1727 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1728 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1729 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1731 /// If a clean shutdown is needed it is recommended to only call
1732 /// this function at a known point where there are no more destructors left
1738 /// use std::process;
1741 /// println!("aborting");
1743 /// process::abort();
1745 /// // execution never gets here
1749 /// The `abort` function terminates the process, so the destructor will not
1750 /// get run on the example below:
1753 /// use std::process;
1757 /// impl Drop for HasDrop {
1758 /// fn drop(&mut self) {
1759 /// println!("This will never be printed!");
1764 /// let _x = HasDrop;
1765 /// process::abort();
1766 /// // the destructor implemented for HasDrop will never get run
1770 /// [panic hook]: crate::panic::set_hook
1771 #[stable(feature = "process_abort", since = "1.17.0")]
1772 pub fn abort() -> ! {
1773 crate::sys::abort_internal();
1776 /// Returns the OS-assigned process identifier associated with this process.
1783 /// use std::process;
1785 /// println!("My pid is {}", process::id());
1789 #[stable(feature = "getpid", since = "1.26.0")]
1790 pub fn id() -> u32 {
1791 crate::sys::os::getpid()
1794 /// A trait for implementing arbitrary return types in the `main` function.
1796 /// The C-main function only supports to return integers as return type.
1797 /// So, every type implementing the `Termination` trait has to be converted
1800 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1801 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1802 #[cfg_attr(not(test), lang = "termination")]
1803 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1804 #[rustc_on_unimplemented(
1805 message = "`main` has invalid return type `{Self}`",
1806 label = "`main` can only return types that implement `{Termination}`"
1808 pub trait Termination {
1809 /// Is called to get the representation of the value as status code.
1810 /// This status code is returned to the operating system.
1811 fn report(self) -> i32;
1814 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1815 impl Termination for () {
1817 fn report(self) -> i32 {
1818 ExitCode::SUCCESS.report()
1822 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1823 impl<E: fmt::Debug> Termination for Result<(), E> {
1824 fn report(self) -> i32 {
1826 Ok(()) => ().report(),
1827 Err(err) => Err::<!, _>(err).report(),
1832 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1833 impl Termination for ! {
1834 fn report(self) -> i32 {
1839 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1840 impl<E: fmt::Debug> Termination for Result<!, E> {
1841 fn report(self) -> i32 {
1842 let Err(err) = self;
1843 eprintln!("Error: {:?}", err);
1844 ExitCode::FAILURE.report()
1848 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1849 impl Termination for ExitCode {
1851 fn report(self) -> i32 {