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 = "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")]
501 /// Allows extension traits within `std`.
502 #[unstable(feature = "sealed", issue = "none")]
503 impl crate::sealed::Sealed for Command {}
506 /// Constructs a new `Command` for launching the program at
507 /// path `program`, with the following default configuration:
509 /// * No arguments to the program
510 /// * Inherit the current process's environment
511 /// * Inherit the current process's working directory
512 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
514 /// Builder methods are provided to change these defaults and
515 /// otherwise configure the process.
517 /// If `program` is not an absolute path, the `PATH` will be searched in
518 /// an OS-defined way.
520 /// The search path to be used may be controlled by setting the
521 /// `PATH` environment variable on the Command,
522 /// but this has some implementation limitations on Windows
523 /// (see issue #37519).
530 /// use std::process::Command;
532 /// Command::new("sh")
534 /// .expect("sh command failed to start");
536 #[stable(feature = "process", since = "1.0.0")]
537 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
538 Command { inner: imp::Command::new(program.as_ref()) }
541 /// Adds an argument to pass to the program.
543 /// Only one argument can be passed per use. So instead of:
546 /// # std::process::Command::new("sh")
547 /// .arg("-C /path/to/repo")
554 /// # std::process::Command::new("sh")
556 /// .arg("/path/to/repo")
560 /// To pass multiple arguments see [`args`].
562 /// [`args`]: Command::args
564 /// Note that the argument is not passed through a shell, but given
565 /// literally to the program. This means that shell syntax like quotes,
566 /// escaped characters, word splitting, glob patterns, substitution, etc.
574 /// use std::process::Command;
576 /// Command::new("ls")
580 /// .expect("ls command failed to start");
582 #[stable(feature = "process", since = "1.0.0")]
583 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
584 self.inner.arg(arg.as_ref());
588 /// Adds multiple arguments to pass to the program.
590 /// To pass a single argument see [`arg`].
592 /// [`arg`]: Command::arg
594 /// Note that the arguments are not passed through a shell, but given
595 /// literally to the program. This means that shell syntax like quotes,
596 /// escaped characters, word splitting, glob patterns, substitution, etc.
604 /// use std::process::Command;
606 /// Command::new("ls")
607 /// .args(&["-l", "-a"])
609 /// .expect("ls command failed to start");
611 #[stable(feature = "process", since = "1.0.0")]
612 pub fn args<I, S>(&mut self, args: I) -> &mut Command
614 I: IntoIterator<Item = S>,
618 self.arg(arg.as_ref());
623 /// Inserts or updates an environment variable mapping.
625 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
626 /// and case-sensitive on all other platforms.
633 /// use std::process::Command;
635 /// Command::new("ls")
636 /// .env("PATH", "/bin")
638 /// .expect("ls command failed to start");
640 #[stable(feature = "process", since = "1.0.0")]
641 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
646 self.inner.env_mut().set(key.as_ref(), val.as_ref());
650 /// Adds or updates multiple environment variable mappings.
657 /// use std::process::{Command, Stdio};
659 /// use std::collections::HashMap;
661 /// let filtered_env : HashMap<String, String> =
662 /// env::vars().filter(|&(ref k, _)|
663 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
666 /// Command::new("printenv")
667 /// .stdin(Stdio::null())
668 /// .stdout(Stdio::inherit())
670 /// .envs(&filtered_env)
672 /// .expect("printenv failed to start");
674 #[stable(feature = "command_envs", since = "1.19.0")]
675 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
677 I: IntoIterator<Item = (K, V)>,
681 for (ref key, ref val) in vars {
682 self.inner.env_mut().set(key.as_ref(), val.as_ref());
687 /// Removes an environment variable mapping.
694 /// use std::process::Command;
696 /// Command::new("ls")
697 /// .env_remove("PATH")
699 /// .expect("ls command failed to start");
701 #[stable(feature = "process", since = "1.0.0")]
702 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
703 self.inner.env_mut().remove(key.as_ref());
707 /// Clears the entire environment map for the child process.
714 /// use std::process::Command;
716 /// Command::new("ls")
719 /// .expect("ls command failed to start");
721 #[stable(feature = "process", since = "1.0.0")]
722 pub fn env_clear(&mut self) -> &mut Command {
723 self.inner.env_mut().clear();
727 /// Sets the working directory for the child process.
729 /// # Platform-specific behavior
731 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
732 /// whether it should be interpreted relative to the parent's working
733 /// directory or relative to `current_dir`. The behavior in this case is
734 /// platform specific and unstable, and it's recommended to use
735 /// [`canonicalize`] to get an absolute program path instead.
742 /// use std::process::Command;
744 /// Command::new("ls")
745 /// .current_dir("/bin")
747 /// .expect("ls command failed to start");
750 /// [`canonicalize`]: crate::fs::canonicalize
751 #[stable(feature = "process", since = "1.0.0")]
752 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
753 self.inner.cwd(dir.as_ref().as_ref());
757 /// Configuration for the child process's standard input (stdin) handle.
759 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
760 /// defaults to [`piped`] when used with `output`.
762 /// [`inherit`]: Stdio::inherit
763 /// [`piped`]: Stdio::piped
770 /// use std::process::{Command, Stdio};
772 /// Command::new("ls")
773 /// .stdin(Stdio::null())
775 /// .expect("ls command failed to start");
777 #[stable(feature = "process", since = "1.0.0")]
778 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
779 self.inner.stdin(cfg.into().0);
783 /// Configuration for the child process's standard output (stdout) handle.
785 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
786 /// defaults to [`piped`] when used with `output`.
788 /// [`inherit`]: Stdio::inherit
789 /// [`piped`]: Stdio::piped
796 /// use std::process::{Command, Stdio};
798 /// Command::new("ls")
799 /// .stdout(Stdio::null())
801 /// .expect("ls command failed to start");
803 #[stable(feature = "process", since = "1.0.0")]
804 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
805 self.inner.stdout(cfg.into().0);
809 /// Configuration for the child process's standard error (stderr) handle.
811 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
812 /// defaults to [`piped`] when used with `output`.
814 /// [`inherit`]: Stdio::inherit
815 /// [`piped`]: Stdio::piped
822 /// use std::process::{Command, Stdio};
824 /// Command::new("ls")
825 /// .stderr(Stdio::null())
827 /// .expect("ls command failed to start");
829 #[stable(feature = "process", since = "1.0.0")]
830 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
831 self.inner.stderr(cfg.into().0);
835 /// Executes the command as a child process, returning a handle to it.
837 /// By default, stdin, stdout and stderr are inherited from the parent.
844 /// use std::process::Command;
846 /// Command::new("ls")
848 /// .expect("ls command failed to start");
850 #[stable(feature = "process", since = "1.0.0")]
851 pub fn spawn(&mut self) -> io::Result<Child> {
852 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
855 /// Executes the command as a child process, waiting for it to finish and
856 /// collecting all of its output.
858 /// By default, stdout and stderr are captured (and used to provide the
859 /// resulting output). Stdin is not inherited from the parent and any
860 /// attempt by the child process to read from the stdin stream will result
861 /// in the stream immediately closing.
866 /// use std::process::Command;
867 /// use std::io::{self, Write};
868 /// let output = Command::new("/bin/cat")
871 /// .expect("failed to execute process");
873 /// println!("status: {}", output.status);
874 /// io::stdout().write_all(&output.stdout).unwrap();
875 /// io::stderr().write_all(&output.stderr).unwrap();
877 /// assert!(output.status.success());
879 #[stable(feature = "process", since = "1.0.0")]
880 pub fn output(&mut self) -> io::Result<Output> {
882 .spawn(imp::Stdio::MakePipe, false)
883 .map(Child::from_inner)
884 .and_then(|p| p.wait_with_output())
887 /// Executes a command as a child process, waiting for it to finish and
888 /// collecting its exit status.
890 /// By default, stdin, stdout and stderr are inherited from the parent.
895 /// use std::process::Command;
897 /// let status = Command::new("/bin/cat")
900 /// .expect("failed to execute process");
902 /// println!("process exited with: {}", status);
904 /// assert!(status.success());
906 #[stable(feature = "process", since = "1.0.0")]
907 pub fn status(&mut self) -> io::Result<ExitStatus> {
909 .spawn(imp::Stdio::Inherit, true)
910 .map(Child::from_inner)
911 .and_then(|mut p| p.wait())
914 /// Returns the path to the program that was given to [`Command::new`].
919 /// # #![feature(command_access)]
920 /// use std::process::Command;
922 /// let cmd = Command::new("echo");
923 /// assert_eq!(cmd.get_program(), "echo");
925 #[unstable(feature = "command_access", issue = "44434")]
926 pub fn get_program(&self) -> &OsStr {
927 self.inner.get_program()
930 /// Returns an iterator of the arguments that will be passed to the program.
932 /// This does not include the path to the program as the first argument;
933 /// it only includes the arguments specified with [`Command::arg`] and
934 /// [`Command::args`].
939 /// # #![feature(command_access)]
940 /// use std::ffi::OsStr;
941 /// use std::process::Command;
943 /// let mut cmd = Command::new("echo");
944 /// cmd.arg("first").arg("second");
945 /// let args: Vec<&OsStr> = cmd.get_args().collect();
946 /// assert_eq!(args, &["first", "second"]);
948 #[unstable(feature = "command_access", issue = "44434")]
949 pub fn get_args(&self) -> CommandArgs<'_> {
950 CommandArgs { inner: self.inner.get_args() }
953 /// Returns an iterator of the environment variables that will be set when
954 /// the process is spawned.
956 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
957 /// value is the key, and the second is the value, which is [`None`] if
958 /// the environment variable is to be explicitly removed.
960 /// This only includes environment variables explicitly set with
961 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
962 /// does not include environment variables that will be inherited by the
968 /// # #![feature(command_access)]
969 /// use std::ffi::OsStr;
970 /// use std::process::Command;
972 /// let mut cmd = Command::new("ls");
973 /// cmd.env("TERM", "dumb").env_remove("TZ");
974 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
975 /// assert_eq!(envs, &[
976 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
977 /// (OsStr::new("TZ"), None)
980 #[unstable(feature = "command_access", issue = "44434")]
981 pub fn get_envs(&self) -> CommandEnvs<'_> {
982 self.inner.get_envs()
985 /// Returns the working directory for the child process.
987 /// This returns [`None`] if the working directory will not be changed.
992 /// # #![feature(command_access)]
993 /// use std::path::Path;
994 /// use std::process::Command;
996 /// let mut cmd = Command::new("ls");
997 /// assert_eq!(cmd.get_current_dir(), None);
998 /// cmd.current_dir("/bin");
999 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1001 #[unstable(feature = "command_access", issue = "44434")]
1002 pub fn get_current_dir(&self) -> Option<&Path> {
1003 self.inner.get_current_dir()
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl fmt::Debug for Command {
1009 /// Format the program and arguments of a Command for display. Any
1010 /// non-utf8 data is lossily converted using the utf8 replacement
1012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017 impl AsInner<imp::Command> for Command {
1018 fn as_inner(&self) -> &imp::Command {
1023 impl AsInnerMut<imp::Command> for Command {
1024 fn as_inner_mut(&mut self) -> &mut imp::Command {
1029 /// An iterator over the command arguments.
1031 /// This struct is created by [`Command::get_args`]. See its documentation for
1033 #[unstable(feature = "command_access", issue = "44434")]
1035 pub struct CommandArgs<'a> {
1036 inner: imp::CommandArgs<'a>,
1039 #[unstable(feature = "command_access", issue = "44434")]
1040 impl<'a> Iterator for CommandArgs<'a> {
1041 type Item = &'a OsStr;
1042 fn next(&mut self) -> Option<&'a OsStr> {
1045 fn size_hint(&self) -> (usize, Option<usize>) {
1046 self.inner.size_hint()
1050 #[unstable(feature = "command_access", issue = "44434")]
1051 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1052 fn len(&self) -> usize {
1055 fn is_empty(&self) -> bool {
1056 self.inner.is_empty()
1060 /// The output of a finished process.
1062 /// This is returned in a Result by either the [`output`] method of a
1063 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1066 /// [`output`]: Command::output
1067 /// [`wait_with_output`]: Child::wait_with_output
1068 #[derive(PartialEq, Eq, Clone)]
1069 #[stable(feature = "process", since = "1.0.0")]
1071 /// The status (exit code) of the process.
1072 #[stable(feature = "process", since = "1.0.0")]
1073 pub status: ExitStatus,
1074 /// The data that the process wrote to stdout.
1075 #[stable(feature = "process", since = "1.0.0")]
1076 pub stdout: Vec<u8>,
1077 /// The data that the process wrote to stderr.
1078 #[stable(feature = "process", since = "1.0.0")]
1079 pub stderr: Vec<u8>,
1082 // If either stderr or stdout are valid utf8 strings it prints the valid
1083 // strings, otherwise it prints the byte sequence instead
1084 #[stable(feature = "process_output_debug", since = "1.7.0")]
1085 impl fmt::Debug for Output {
1086 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1087 let stdout_utf8 = str::from_utf8(&self.stdout);
1088 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1090 Err(_) => &self.stdout,
1093 let stderr_utf8 = str::from_utf8(&self.stderr);
1094 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1096 Err(_) => &self.stderr,
1099 fmt.debug_struct("Output")
1100 .field("status", &self.status)
1101 .field("stdout", stdout_debug)
1102 .field("stderr", stderr_debug)
1107 /// Describes what to do with a standard I/O stream for a child process when
1108 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1110 /// [`stdin`]: Command::stdin
1111 /// [`stdout`]: Command::stdout
1112 /// [`stderr`]: Command::stderr
1113 #[stable(feature = "process", since = "1.0.0")]
1114 pub struct Stdio(imp::Stdio);
1117 /// A new pipe should be arranged to connect the parent and child processes.
1124 /// use std::process::{Command, Stdio};
1126 /// let output = Command::new("echo")
1127 /// .arg("Hello, world!")
1128 /// .stdout(Stdio::piped())
1130 /// .expect("Failed to execute command");
1132 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1133 /// // Nothing echoed to console
1139 /// use std::io::Write;
1140 /// use std::process::{Command, Stdio};
1142 /// let mut child = Command::new("rev")
1143 /// .stdin(Stdio::piped())
1144 /// .stdout(Stdio::piped())
1146 /// .expect("Failed to spawn child process");
1149 /// let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1150 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1153 /// let output = child.wait_with_output().expect("Failed to read stdout");
1154 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1156 #[stable(feature = "process", since = "1.0.0")]
1157 pub fn piped() -> Stdio {
1158 Stdio(imp::Stdio::MakePipe)
1161 /// The child inherits from the corresponding parent descriptor.
1168 /// use std::process::{Command, Stdio};
1170 /// let output = Command::new("echo")
1171 /// .arg("Hello, world!")
1172 /// .stdout(Stdio::inherit())
1174 /// .expect("Failed to execute command");
1176 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1177 /// // "Hello, world!" echoed to console
1183 /// use std::process::{Command, Stdio};
1184 /// use std::io::{self, Write};
1186 /// let output = Command::new("rev")
1187 /// .stdin(Stdio::inherit())
1188 /// .stdout(Stdio::piped())
1190 /// .expect("Failed to execute command");
1192 /// print!("You piped in the reverse of: ");
1193 /// io::stdout().write_all(&output.stdout).unwrap();
1195 #[stable(feature = "process", since = "1.0.0")]
1196 pub fn inherit() -> Stdio {
1197 Stdio(imp::Stdio::Inherit)
1200 /// This stream will be ignored. This is the equivalent of attaching the
1201 /// stream to `/dev/null`.
1208 /// use std::process::{Command, Stdio};
1210 /// let output = Command::new("echo")
1211 /// .arg("Hello, world!")
1212 /// .stdout(Stdio::null())
1214 /// .expect("Failed to execute command");
1216 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1217 /// // Nothing echoed to console
1223 /// use std::process::{Command, Stdio};
1225 /// let output = Command::new("rev")
1226 /// .stdin(Stdio::null())
1227 /// .stdout(Stdio::piped())
1229 /// .expect("Failed to execute command");
1231 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1232 /// // Ignores any piped-in input
1234 #[stable(feature = "process", since = "1.0.0")]
1235 pub fn null() -> Stdio {
1236 Stdio(imp::Stdio::Null)
1240 impl FromInner<imp::Stdio> for Stdio {
1241 fn from_inner(inner: imp::Stdio) -> Stdio {
1246 #[stable(feature = "std_debug", since = "1.16.0")]
1247 impl fmt::Debug for Stdio {
1248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1249 f.pad("Stdio { .. }")
1253 #[stable(feature = "stdio_from", since = "1.20.0")]
1254 impl From<ChildStdin> for Stdio {
1255 /// Converts a `ChildStdin` into a `Stdio`
1259 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1262 /// use std::process::{Command, Stdio};
1264 /// let reverse = Command::new("rev")
1265 /// .stdin(Stdio::piped())
1267 /// .expect("failed reverse command");
1269 /// let _echo = Command::new("echo")
1270 /// .arg("Hello, world!")
1271 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1273 /// .expect("failed echo command");
1275 /// // "!dlrow ,olleH" echoed to console
1277 fn from(child: ChildStdin) -> Stdio {
1278 Stdio::from_inner(child.into_inner().into())
1282 #[stable(feature = "stdio_from", since = "1.20.0")]
1283 impl From<ChildStdout> for Stdio {
1284 /// Converts a `ChildStdout` into a `Stdio`
1288 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1291 /// use std::process::{Command, Stdio};
1293 /// let hello = Command::new("echo")
1294 /// .arg("Hello, world!")
1295 /// .stdout(Stdio::piped())
1297 /// .expect("failed echo command");
1299 /// let reverse = Command::new("rev")
1300 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1302 /// .expect("failed reverse command");
1304 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1306 fn from(child: ChildStdout) -> Stdio {
1307 Stdio::from_inner(child.into_inner().into())
1311 #[stable(feature = "stdio_from", since = "1.20.0")]
1312 impl From<ChildStderr> for Stdio {
1313 /// Converts a `ChildStderr` into a `Stdio`
1318 /// use std::process::{Command, Stdio};
1320 /// let reverse = Command::new("rev")
1321 /// .arg("non_existing_file.txt")
1322 /// .stderr(Stdio::piped())
1324 /// .expect("failed reverse command");
1326 /// let cat = Command::new("cat")
1328 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1330 /// .expect("failed echo command");
1333 /// String::from_utf8_lossy(&cat.stdout),
1334 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1337 fn from(child: ChildStderr) -> Stdio {
1338 Stdio::from_inner(child.into_inner().into())
1342 #[stable(feature = "stdio_from", since = "1.20.0")]
1343 impl From<fs::File> for Stdio {
1344 /// Converts a `File` into a `Stdio`
1348 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1351 /// use std::fs::File;
1352 /// use std::process::Command;
1354 /// // With the `foo.txt` file containing `Hello, world!"
1355 /// let file = File::open("foo.txt").unwrap();
1357 /// let reverse = Command::new("rev")
1358 /// .stdin(file) // Implicit File conversion into a Stdio
1360 /// .expect("failed reverse command");
1362 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1364 fn from(file: fs::File) -> Stdio {
1365 Stdio::from_inner(file.into_inner().into())
1369 /// Describes the result of a process after it has terminated.
1371 /// This `struct` is used to represent the exit status of a child process.
1372 /// Child processes are created via the [`Command`] struct and their exit
1373 /// status is exposed through the [`status`] method, or the [`wait`] method
1374 /// of a [`Child`] process.
1376 /// [`status`]: Command::status
1377 /// [`wait`]: Child::wait
1378 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1379 #[stable(feature = "process", since = "1.0.0")]
1380 pub struct ExitStatus(imp::ExitStatus);
1382 /// Allows extension traits within `std`.
1383 #[unstable(feature = "sealed", issue = "none")]
1384 impl crate::sealed::Sealed for ExitStatus {}
1387 /// Was termination successful? Signal termination is not considered a
1388 /// success, and success is defined as a zero exit status.
1393 /// use std::process::Command;
1395 /// let status = Command::new("mkdir")
1396 /// .arg("projects")
1398 /// .expect("failed to execute mkdir");
1400 /// if status.success() {
1401 /// println!("'projects/' directory created");
1403 /// println!("failed to create 'projects/' directory");
1406 #[stable(feature = "process", since = "1.0.0")]
1407 pub fn success(&self) -> bool {
1411 /// Returns the exit code of the process, if any.
1413 /// On Unix, this will return `None` if the process was terminated
1414 /// by a signal; `std::os::unix` provides an extension trait for
1415 /// extracting the signal and other details from the `ExitStatus`.
1420 /// use std::process::Command;
1422 /// let status = Command::new("mkdir")
1423 /// .arg("projects")
1425 /// .expect("failed to execute mkdir");
1427 /// match status.code() {
1428 /// Some(code) => println!("Exited with status code: {}", code),
1429 /// None => println!("Process terminated by signal")
1432 #[stable(feature = "process", since = "1.0.0")]
1433 pub fn code(&self) -> Option<i32> {
1438 impl AsInner<imp::ExitStatus> for ExitStatus {
1439 fn as_inner(&self) -> &imp::ExitStatus {
1444 impl FromInner<imp::ExitStatus> for ExitStatus {
1445 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1450 #[stable(feature = "process", since = "1.0.0")]
1451 impl fmt::Display for ExitStatus {
1452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1457 /// This type represents the status code a process can return to its
1458 /// parent under normal termination.
1460 /// Numeric values used in this type don't have portable meanings, and
1461 /// different platforms may mask different amounts of them.
1463 /// For the platform's canonical successful and unsuccessful codes, see
1464 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1466 /// [`SUCCESS`]: ExitCode::SUCCESS
1467 /// [`FAILURE`]: ExitCode::FAILURE
1469 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1470 /// it was ultimately cut from that RFC, and thus this type is more subject
1471 /// to change even than the usual unstable item churn.
1473 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1474 #[derive(Clone, Copy, Debug)]
1475 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1476 pub struct ExitCode(imp::ExitCode);
1478 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1480 /// The canonical ExitCode for successful termination on this platform.
1482 /// Note that a `()`-returning `main` implicitly results in a successful
1483 /// termination, so there's no need to return this from `main` unless
1484 /// you're also returning other possible codes.
1485 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1486 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1488 /// The canonical ExitCode for unsuccessful termination on this platform.
1490 /// If you're only returning this and `SUCCESS` from `main`, consider
1491 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1492 /// return the same codes (but will also `eprintln!` the error).
1493 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1494 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1498 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1499 /// error is returned.
1501 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1502 /// especially the [`Other`] kind might change to more specific kinds in the future.
1504 /// This is equivalent to sending a SIGKILL on Unix platforms.
1511 /// use std::process::Command;
1513 /// let mut command = Command::new("yes");
1514 /// if let Ok(mut child) = command.spawn() {
1515 /// child.kill().expect("command wasn't running");
1517 /// println!("yes command didn't start");
1521 /// [`ErrorKind`]: io::ErrorKind
1522 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1523 /// [`Other`]: io::ErrorKind::Other
1524 #[stable(feature = "process", since = "1.0.0")]
1525 pub fn kill(&mut self) -> io::Result<()> {
1529 /// Returns the OS-assigned process identifier associated with this child.
1536 /// use std::process::Command;
1538 /// let mut command = Command::new("ls");
1539 /// if let Ok(child) = command.spawn() {
1540 /// println!("Child's ID is {}", child.id());
1542 /// println!("ls command didn't start");
1545 #[stable(feature = "process_id", since = "1.3.0")]
1546 pub fn id(&self) -> u32 {
1550 /// Waits for the child to exit completely, returning the status that it
1551 /// exited with. This function will continue to have the same return value
1552 /// after it has been called at least once.
1554 /// The stdin handle to the child process, if any, will be closed
1555 /// before waiting. This helps avoid deadlock: it ensures that the
1556 /// child does not block waiting for input from the parent, while
1557 /// the parent waits for the child to exit.
1564 /// use std::process::Command;
1566 /// let mut command = Command::new("ls");
1567 /// if let Ok(mut child) = command.spawn() {
1568 /// child.wait().expect("command wasn't running");
1569 /// println!("Child has finished its execution!");
1571 /// println!("ls command didn't start");
1574 #[stable(feature = "process", since = "1.0.0")]
1575 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1576 drop(self.stdin.take());
1577 self.handle.wait().map(ExitStatus)
1580 /// Attempts to collect the exit status of the child if it has already
1583 /// This function will not block the calling thread and will only
1584 /// check to see if the child process has exited or not. If the child has
1585 /// exited then on Unix the process ID is reaped. This function is
1586 /// guaranteed to repeatedly return a successful exit status so long as the
1587 /// child has already exited.
1589 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1590 /// exit status is not available at this time then `Ok(None)` is returned.
1591 /// If an error occurs, then that error is returned.
1593 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1600 /// use std::process::Command;
1602 /// let mut child = Command::new("ls").spawn().unwrap();
1604 /// match child.try_wait() {
1605 /// Ok(Some(status)) => println!("exited with: {}", status),
1607 /// println!("status not ready yet, let's really wait");
1608 /// let res = child.wait();
1609 /// println!("result: {:?}", res);
1611 /// Err(e) => println!("error attempting to wait: {}", e),
1614 #[stable(feature = "process_try_wait", since = "1.18.0")]
1615 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1616 Ok(self.handle.try_wait()?.map(ExitStatus))
1619 /// Simultaneously waits for the child to exit and collect all remaining
1620 /// output on the stdout/stderr handles, returning an `Output`
1623 /// The stdin handle to the child process, if any, will be closed
1624 /// before waiting. This helps avoid deadlock: it ensures that the
1625 /// child does not block waiting for input from the parent, while
1626 /// the parent waits for the child to exit.
1628 /// By default, stdin, stdout and stderr are inherited from the parent.
1629 /// In order to capture the output into this `Result<Output>` it is
1630 /// necessary to create new pipes between parent and child. Use
1631 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1636 /// use std::process::{Command, Stdio};
1638 /// let child = Command::new("/bin/cat")
1639 /// .arg("file.txt")
1640 /// .stdout(Stdio::piped())
1642 /// .expect("failed to execute child");
1644 /// let output = child
1645 /// .wait_with_output()
1646 /// .expect("failed to wait on child");
1648 /// assert!(output.status.success());
1651 #[stable(feature = "process", since = "1.0.0")]
1652 pub fn wait_with_output(mut self) -> io::Result<Output> {
1653 drop(self.stdin.take());
1655 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1656 match (self.stdout.take(), self.stderr.take()) {
1658 (Some(mut out), None) => {
1659 let res = out.read_to_end(&mut stdout);
1662 (None, Some(mut err)) => {
1663 let res = err.read_to_end(&mut stderr);
1666 (Some(out), Some(err)) => {
1667 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1672 let status = self.wait()?;
1673 Ok(Output { status, stdout, stderr })
1677 /// Terminates the current process with the specified exit code.
1679 /// This function will never return and will immediately terminate the current
1680 /// process. The exit code is passed through to the underlying OS and will be
1681 /// available for consumption by another process.
1683 /// Note that because this function never returns, and that it terminates the
1684 /// process, no destructors on the current stack or any other thread's stack
1685 /// will be run. If a clean shutdown is needed it is recommended to only call
1686 /// this function at a known point where there are no more destructors left
1689 /// ## Platform-specific behavior
1691 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1692 /// will be visible to a parent process inspecting the exit code. On most
1693 /// Unix-like platforms, only the eight least-significant bits are considered.
1697 /// Due to this function’s behavior regarding destructors, a conventional way
1698 /// to use the function is to extract the actual computation to another
1699 /// function and compute the exit code from its return value:
1702 /// fn run_app() -> Result<(), ()> {
1703 /// // Application logic here
1708 /// std::process::exit(match run_app() {
1711 /// eprintln!("error: {:?}", err);
1718 /// Due to [platform-specific behavior], the exit code for this example will be
1719 /// `0` on Linux, but `256` on Windows:
1722 /// use std::process;
1724 /// process::exit(0x0100);
1727 /// [platform-specific behavior]: #platform-specific-behavior
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub fn exit(code: i32) -> ! {
1730 crate::sys_common::cleanup();
1731 crate::sys::os::exit(code)
1734 /// Terminates the process in an abnormal fashion.
1736 /// The function will never return and will immediately terminate the current
1737 /// process in a platform specific "abnormal" manner.
1739 /// Note that because this function never returns, and that it terminates the
1740 /// process, no destructors on the current stack or any other thread's stack
1743 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1744 /// the current thread's stack and calls all destructors.
1745 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1746 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1747 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1749 /// If a clean shutdown is needed it is recommended to only call
1750 /// this function at a known point where there are no more destructors left
1756 /// use std::process;
1759 /// println!("aborting");
1761 /// process::abort();
1763 /// // execution never gets here
1767 /// The `abort` function terminates the process, so the destructor will not
1768 /// get run on the example below:
1771 /// use std::process;
1775 /// impl Drop for HasDrop {
1776 /// fn drop(&mut self) {
1777 /// println!("This will never be printed!");
1782 /// let _x = HasDrop;
1783 /// process::abort();
1784 /// // the destructor implemented for HasDrop will never get run
1788 /// [panic hook]: crate::panic::set_hook
1789 #[stable(feature = "process_abort", since = "1.17.0")]
1791 pub fn abort() -> ! {
1792 crate::sys::abort_internal();
1795 /// Returns the OS-assigned process identifier associated with this process.
1802 /// use std::process;
1804 /// println!("My pid is {}", process::id());
1808 #[stable(feature = "getpid", since = "1.26.0")]
1809 pub fn id() -> u32 {
1810 crate::sys::os::getpid()
1813 /// A trait for implementing arbitrary return types in the `main` function.
1815 /// The C-main function only supports to return integers as return type.
1816 /// So, every type implementing the `Termination` trait has to be converted
1819 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1820 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1821 #[cfg_attr(not(test), lang = "termination")]
1822 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1823 #[rustc_on_unimplemented(
1824 message = "`main` has invalid return type `{Self}`",
1825 label = "`main` can only return types that implement `{Termination}`"
1827 pub trait Termination {
1828 /// Is called to get the representation of the value as status code.
1829 /// This status code is returned to the operating system.
1830 fn report(self) -> i32;
1833 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1834 impl Termination for () {
1836 fn report(self) -> i32 {
1837 ExitCode::SUCCESS.report()
1841 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1842 impl<E: fmt::Debug> Termination for Result<(), E> {
1843 fn report(self) -> i32 {
1845 Ok(()) => ().report(),
1846 Err(err) => Err::<!, _>(err).report(),
1851 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1852 impl Termination for ! {
1853 fn report(self) -> i32 {
1858 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1859 impl<E: fmt::Debug> Termination for Result<!, E> {
1860 fn report(self) -> i32 {
1861 let Err(err) = self;
1862 eprintln!("Error: {:?}", err);
1863 ExitCode::FAILURE.report()
1867 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1868 impl Termination for ExitCode {
1870 fn report(self) -> i32 {