1 //! A module for working with processes.
3 //! This module is mostly concerned with spawning and interacting with child
4 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
7 //! # Spawning a process
9 //! The [`Command`] struct is used to configure and spawn processes:
12 //! use std::process::Command;
14 //! let output = Command::new("echo")
15 //! .arg("Hello world")
17 //! .expect("Failed to execute command");
19 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
22 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
23 //! to spawn a process. In particular, [`output`] spawns the child process and
24 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
25 //! that represents the spawned child process.
29 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
30 //! configured by passing an [`Stdio`] to the corresponding method on
31 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
32 //! example, piping output from one command into another command can be done
36 //! use std::process::{Command, Stdio};
38 //! // stdout must be configured with `Stdio::piped` in order to use
39 //! // `echo_child.stdout`
40 //! let echo_child = Command::new("echo")
41 //! .arg("Oh no, a tpyo!")
42 //! .stdout(Stdio::piped())
44 //! .expect("Failed to start echo process");
46 //! // Note that `echo_child` is moved here, but we won't be needing
47 //! // `echo_child` anymore
48 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
50 //! let mut sed_child = Command::new("sed")
51 //! .arg("s/tpyo/typo/")
52 //! .stdin(Stdio::from(echo_out))
53 //! .stdout(Stdio::piped())
55 //! .expect("Failed to start sed process");
57 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
58 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
61 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
62 //! [`ChildStdin`] implements [`Write`]:
65 //! use std::process::{Command, Stdio};
66 //! use std::io::Write;
68 //! let mut child = Command::new("/bin/cat")
69 //! .stdin(Stdio::piped())
70 //! .stdout(Stdio::piped())
72 //! .expect("failed to execute child");
74 //! // If the child process fills its stdout buffer, it may end up
75 //! // waiting until the parent reads the stdout, and not be able to
76 //! // read stdin in the meantime, causing a deadlock.
77 //! // Writing from another thread ensures that stdout is being read
78 //! // at the same time, avoiding the problem.
79 //! let mut stdin = child.stdin.take().expect("failed to get stdin");
80 //! std::thread::spawn(move || {
81 //! stdin.write_all(b"test").expect("failed to write to stdin");
84 //! let output = child
85 //! .wait_with_output()
86 //! .expect("failed to wait on child");
88 //! assert_eq!(b"test", output.stdout.as_slice());
91 //! [`spawn`]: Command::spawn
92 //! [`output`]: Command::output
94 //! [`stdout`]: Command::stdout
95 //! [`stdin`]: Command::stdin
96 //! [`stderr`]: Command::stderr
98 //! [`Write`]: io::Write
99 //! [`Read`]: io::Read
101 #![stable(feature = "process", since = "1.0.0")]
102 #![deny(unsafe_op_in_unsafe_fn)]
104 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
107 use crate::io::prelude::*;
109 use crate::ffi::OsStr;
112 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
113 use crate::path::Path;
115 use crate::sys::pipe::{read2, AnonPipe};
116 use crate::sys::process as imp;
117 #[unstable(feature = "command_access", issue = "44434")]
118 pub use crate::sys_common::process::CommandEnvs;
119 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
121 /// Representation of a running or exited child process.
123 /// This structure is used to represent and manage child processes. A child
124 /// process is created via the [`Command`] struct, which configures the
125 /// spawning process and can itself be constructed using a builder-style
128 /// There is no implementation of [`Drop`] for child processes,
129 /// so if you do not ensure the `Child` has exited then it will continue to
130 /// run, even after the `Child` handle to the child process has gone out of
133 /// Calling [`wait`] (or other functions that wrap around it) will make
134 /// the parent process wait until the child has actually exited before
139 /// On some systems, calling [`wait`] or similar is necessary for the OS to
140 /// release resources. A process that terminated but has not been waited on is
141 /// still around as a "zombie". Leaving too many zombies around may exhaust
142 /// global resources (for example process IDs).
144 /// The standard library does *not* automatically wait on child processes (not
145 /// even if the `Child` is dropped), it is up to the application developer to do
146 /// so. As a consequence, dropping `Child` handles without waiting on them first
147 /// is not recommended in long-running applications.
152 /// use std::process::Command;
154 /// let mut child = Command::new("/bin/cat")
157 /// .expect("failed to execute child");
159 /// let ecode = child.wait()
160 /// .expect("failed to wait on child");
162 /// assert!(ecode.success());
165 /// [`wait`]: Child::wait
166 #[stable(feature = "process", since = "1.0.0")]
168 handle: imp::Process,
170 /// The handle for writing to the child's standard input (stdin), if it has
171 /// been captured. To avoid partially moving
172 /// the `child` and thus blocking yourself from calling
173 /// functions on `child` while using `stdin`,
174 /// you might find it helpful:
176 /// ```compile_fail,E0425
177 /// let stdin = child.stdin.take().unwrap();
179 #[stable(feature = "process", since = "1.0.0")]
180 pub stdin: Option<ChildStdin>,
182 /// The handle for reading from the child's standard output (stdout), if it
183 /// has been captured. You might find it helpful to do
185 /// ```compile_fail,E0425
186 /// let stdout = child.stdout.take().unwrap();
189 /// to avoid partially moving the `child` and thus blocking yourself from calling
190 /// functions on `child` while using `stdout`.
191 #[stable(feature = "process", since = "1.0.0")]
192 pub stdout: Option<ChildStdout>,
194 /// The handle for reading from the child's standard error (stderr), if it
195 /// has been captured. You might find it helpful to do
197 /// ```compile_fail,E0425
198 /// let stderr = child.stderr.take().unwrap();
201 /// to avoid partially moving the `child` and thus blocking yourself from calling
202 /// functions on `child` while using `stderr`.
203 #[stable(feature = "process", since = "1.0.0")]
204 pub stderr: Option<ChildStderr>,
207 impl AsInner<imp::Process> for Child {
208 fn as_inner(&self) -> &imp::Process {
213 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
214 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
217 stdin: io.stdin.map(ChildStdin::from_inner),
218 stdout: io.stdout.map(ChildStdout::from_inner),
219 stderr: io.stderr.map(ChildStderr::from_inner),
224 impl IntoInner<imp::Process> for Child {
225 fn into_inner(self) -> imp::Process {
230 #[stable(feature = "std_debug", since = "1.16.0")]
231 impl fmt::Debug for Child {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233 f.debug_struct("Child")
234 .field("stdin", &self.stdin)
235 .field("stdout", &self.stdout)
236 .field("stderr", &self.stderr)
241 /// A handle to a child process's standard input (stdin).
243 /// This struct is used in the [`stdin`] field on [`Child`].
245 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
246 /// file handle will be closed. If the child process was blocked on input prior
247 /// to being dropped, it will become unblocked after dropping.
249 /// [`stdin`]: Child::stdin
251 #[stable(feature = "process", since = "1.0.0")]
252 pub struct ChildStdin {
256 #[stable(feature = "process", since = "1.0.0")]
257 impl Write for ChildStdin {
258 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
262 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
263 (&*self).write_vectored(bufs)
266 fn is_write_vectored(&self) -> bool {
267 io::Write::is_write_vectored(&&*self)
270 fn flush(&mut self) -> io::Result<()> {
275 #[stable(feature = "write_mt", since = "1.48.0")]
276 impl Write for &ChildStdin {
277 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
278 self.inner.write(buf)
281 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
282 self.inner.write_vectored(bufs)
285 fn is_write_vectored(&self) -> bool {
286 self.inner.is_write_vectored()
289 fn flush(&mut self) -> io::Result<()> {
294 impl AsInner<AnonPipe> for ChildStdin {
295 fn as_inner(&self) -> &AnonPipe {
300 impl IntoInner<AnonPipe> for ChildStdin {
301 fn into_inner(self) -> AnonPipe {
306 impl FromInner<AnonPipe> for ChildStdin {
307 fn from_inner(pipe: AnonPipe) -> ChildStdin {
308 ChildStdin { inner: pipe }
312 #[stable(feature = "std_debug", since = "1.16.0")]
313 impl fmt::Debug for ChildStdin {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 f.pad("ChildStdin { .. }")
319 /// A handle to a child process's standard output (stdout).
321 /// This struct is used in the [`stdout`] field on [`Child`].
323 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
324 /// underlying file handle will be closed.
326 /// [`stdout`]: Child::stdout
328 #[stable(feature = "process", since = "1.0.0")]
329 pub struct ChildStdout {
333 #[stable(feature = "process", since = "1.0.0")]
334 impl Read for ChildStdout {
335 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
339 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
340 self.inner.read_vectored(bufs)
344 fn is_read_vectored(&self) -> bool {
345 self.inner.is_read_vectored()
349 unsafe fn initializer(&self) -> Initializer {
350 // SAFETY: Read is guaranteed to work on uninitialized memory
351 unsafe { Initializer::nop() }
355 impl AsInner<AnonPipe> for ChildStdout {
356 fn as_inner(&self) -> &AnonPipe {
361 impl IntoInner<AnonPipe> for ChildStdout {
362 fn into_inner(self) -> AnonPipe {
367 impl FromInner<AnonPipe> for ChildStdout {
368 fn from_inner(pipe: AnonPipe) -> ChildStdout {
369 ChildStdout { inner: pipe }
373 #[stable(feature = "std_debug", since = "1.16.0")]
374 impl fmt::Debug for ChildStdout {
375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 f.pad("ChildStdout { .. }")
380 /// A handle to a child process's stderr.
382 /// This struct is used in the [`stderr`] field on [`Child`].
384 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
385 /// underlying file handle will be closed.
387 /// [`stderr`]: Child::stderr
389 #[stable(feature = "process", since = "1.0.0")]
390 pub struct ChildStderr {
394 #[stable(feature = "process", since = "1.0.0")]
395 impl Read for ChildStderr {
396 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
400 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
401 self.inner.read_vectored(bufs)
405 fn is_read_vectored(&self) -> bool {
406 self.inner.is_read_vectored()
410 unsafe fn initializer(&self) -> Initializer {
411 // SAFETY: Read is guaranteed to work on uninitialized memory
412 unsafe { Initializer::nop() }
416 impl AsInner<AnonPipe> for ChildStderr {
417 fn as_inner(&self) -> &AnonPipe {
422 impl IntoInner<AnonPipe> for ChildStderr {
423 fn into_inner(self) -> AnonPipe {
428 impl FromInner<AnonPipe> for ChildStderr {
429 fn from_inner(pipe: AnonPipe) -> ChildStderr {
430 ChildStderr { inner: pipe }
434 #[stable(feature = "std_debug", since = "1.16.0")]
435 impl fmt::Debug for ChildStderr {
436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437 f.pad("ChildStderr { .. }")
441 /// A process builder, providing fine-grained control
442 /// over how a new process should be spawned.
444 /// A default configuration can be
445 /// generated using `Command::new(program)`, where `program` gives a path to the
446 /// program to be executed. Additional builder methods allow the configuration
447 /// to be changed (for example, by adding arguments) prior to spawning:
450 /// use std::process::Command;
452 /// let output = if cfg!(target_os = "windows") {
453 /// Command::new("cmd")
454 /// .args(&["/C", "echo hello"])
456 /// .expect("failed to execute process")
458 /// Command::new("sh")
460 /// .arg("echo hello")
462 /// .expect("failed to execute process")
465 /// let hello = output.stdout;
468 /// `Command` can be reused to spawn multiple processes. The builder methods
469 /// change the command without needing to immediately spawn the process.
472 /// use std::process::Command;
474 /// let mut echo_hello = Command::new("sh");
475 /// echo_hello.arg("-c")
476 /// .arg("echo hello");
477 /// let hello_1 = echo_hello.output().expect("failed to execute process");
478 /// let hello_2 = echo_hello.output().expect("failed to execute process");
481 /// Similarly, you can call builder methods after spawning a process and then
482 /// spawn a new process with the modified settings.
485 /// use std::process::Command;
487 /// let mut list_dir = Command::new("ls");
489 /// // Execute `ls` in the current directory of the program.
490 /// list_dir.status().expect("process failed to execute");
494 /// // Change `ls` to execute in the root directory.
495 /// list_dir.current_dir("/");
497 /// // And then execute `ls` again but in the root directory.
498 /// list_dir.status().expect("process failed to execute");
500 #[stable(feature = "process", since = "1.0.0")]
505 /// Allows extension traits within `std`.
506 #[unstable(feature = "sealed", issue = "none")]
507 impl crate::sealed::Sealed for Command {}
510 /// Constructs a new `Command` for launching the program at
511 /// path `program`, with the following default configuration:
513 /// * No arguments to the program
514 /// * Inherit the current process's environment
515 /// * Inherit the current process's working directory
516 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
518 /// Builder methods are provided to change these defaults and
519 /// otherwise configure the process.
521 /// If `program` is not an absolute path, the `PATH` will be searched in
522 /// an OS-defined way.
524 /// The search path to be used may be controlled by setting the
525 /// `PATH` environment variable on the Command,
526 /// but this has some implementation limitations on Windows
527 /// (see issue #37519).
534 /// use std::process::Command;
536 /// Command::new("sh")
538 /// .expect("sh command failed to start");
540 #[stable(feature = "process", since = "1.0.0")]
541 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
542 Command { inner: imp::Command::new(program.as_ref()) }
545 /// Adds an argument to pass to the program.
547 /// Only one argument can be passed per use. So instead of:
550 /// # std::process::Command::new("sh")
551 /// .arg("-C /path/to/repo")
558 /// # std::process::Command::new("sh")
560 /// .arg("/path/to/repo")
564 /// To pass multiple arguments see [`args`].
566 /// [`args`]: Command::args
568 /// Note that the argument is not passed through a shell, but given
569 /// literally to the program. This means that shell syntax like quotes,
570 /// escaped characters, word splitting, glob patterns, substitution, etc.
578 /// use std::process::Command;
580 /// Command::new("ls")
584 /// .expect("ls command failed to start");
586 #[stable(feature = "process", since = "1.0.0")]
587 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
588 self.inner.arg(arg.as_ref());
592 /// Adds multiple arguments to pass to the program.
594 /// To pass a single argument see [`arg`].
596 /// [`arg`]: Command::arg
598 /// Note that the arguments are not passed through a shell, but given
599 /// literally to the program. This means that shell syntax like quotes,
600 /// escaped characters, word splitting, glob patterns, substitution, etc.
608 /// use std::process::Command;
610 /// Command::new("ls")
611 /// .args(&["-l", "-a"])
613 /// .expect("ls command failed to start");
615 #[stable(feature = "process", since = "1.0.0")]
616 pub fn args<I, S>(&mut self, args: I) -> &mut Command
618 I: IntoIterator<Item = S>,
622 self.arg(arg.as_ref());
627 /// Inserts or updates an environment variable mapping.
629 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
630 /// and case-sensitive on all other platforms.
637 /// use std::process::Command;
639 /// Command::new("ls")
640 /// .env("PATH", "/bin")
642 /// .expect("ls command failed to start");
644 #[stable(feature = "process", since = "1.0.0")]
645 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
650 self.inner.env_mut().set(key.as_ref(), val.as_ref());
654 /// Adds or updates multiple environment variable mappings.
661 /// use std::process::{Command, Stdio};
663 /// use std::collections::HashMap;
665 /// let filtered_env : HashMap<String, String> =
666 /// env::vars().filter(|&(ref k, _)|
667 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
670 /// Command::new("printenv")
671 /// .stdin(Stdio::null())
672 /// .stdout(Stdio::inherit())
674 /// .envs(&filtered_env)
676 /// .expect("printenv failed to start");
678 #[stable(feature = "command_envs", since = "1.19.0")]
679 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
681 I: IntoIterator<Item = (K, V)>,
685 for (ref key, ref val) in vars {
686 self.inner.env_mut().set(key.as_ref(), val.as_ref());
691 /// Removes an environment variable mapping.
698 /// use std::process::Command;
700 /// Command::new("ls")
701 /// .env_remove("PATH")
703 /// .expect("ls command failed to start");
705 #[stable(feature = "process", since = "1.0.0")]
706 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
707 self.inner.env_mut().remove(key.as_ref());
711 /// Clears the entire environment map for the child process.
718 /// use std::process::Command;
720 /// Command::new("ls")
723 /// .expect("ls command failed to start");
725 #[stable(feature = "process", since = "1.0.0")]
726 pub fn env_clear(&mut self) -> &mut Command {
727 self.inner.env_mut().clear();
731 /// Sets the working directory for the child process.
733 /// # Platform-specific behavior
735 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
736 /// whether it should be interpreted relative to the parent's working
737 /// directory or relative to `current_dir`. The behavior in this case is
738 /// platform specific and unstable, and it's recommended to use
739 /// [`canonicalize`] to get an absolute program path instead.
746 /// use std::process::Command;
748 /// Command::new("ls")
749 /// .current_dir("/bin")
751 /// .expect("ls command failed to start");
754 /// [`canonicalize`]: crate::fs::canonicalize
755 #[stable(feature = "process", since = "1.0.0")]
756 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
757 self.inner.cwd(dir.as_ref().as_ref());
761 /// Configuration for the child process's standard input (stdin) handle.
763 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
764 /// defaults to [`piped`] when used with `output`.
766 /// [`inherit`]: Stdio::inherit
767 /// [`piped`]: Stdio::piped
774 /// use std::process::{Command, Stdio};
776 /// Command::new("ls")
777 /// .stdin(Stdio::null())
779 /// .expect("ls command failed to start");
781 #[stable(feature = "process", since = "1.0.0")]
782 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
783 self.inner.stdin(cfg.into().0);
787 /// Configuration for the child process's standard output (stdout) handle.
789 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
790 /// defaults to [`piped`] when used with `output`.
792 /// [`inherit`]: Stdio::inherit
793 /// [`piped`]: Stdio::piped
800 /// use std::process::{Command, Stdio};
802 /// Command::new("ls")
803 /// .stdout(Stdio::null())
805 /// .expect("ls command failed to start");
807 #[stable(feature = "process", since = "1.0.0")]
808 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
809 self.inner.stdout(cfg.into().0);
813 /// Configuration for the child process's standard error (stderr) handle.
815 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
816 /// defaults to [`piped`] when used with `output`.
818 /// [`inherit`]: Stdio::inherit
819 /// [`piped`]: Stdio::piped
826 /// use std::process::{Command, Stdio};
828 /// Command::new("ls")
829 /// .stderr(Stdio::null())
831 /// .expect("ls command failed to start");
833 #[stable(feature = "process", since = "1.0.0")]
834 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
835 self.inner.stderr(cfg.into().0);
839 /// Executes the command as a child process, returning a handle to it.
841 /// By default, stdin, stdout and stderr are inherited from the parent.
848 /// use std::process::Command;
850 /// Command::new("ls")
852 /// .expect("ls command failed to start");
854 #[stable(feature = "process", since = "1.0.0")]
855 pub fn spawn(&mut self) -> io::Result<Child> {
856 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
859 /// Executes the command as a child process, waiting for it to finish and
860 /// collecting all of its output.
862 /// By default, stdout and stderr are captured (and used to provide the
863 /// resulting output). Stdin is not inherited from the parent and any
864 /// attempt by the child process to read from the stdin stream will result
865 /// in the stream immediately closing.
870 /// use std::process::Command;
871 /// use std::io::{self, Write};
872 /// let output = Command::new("/bin/cat")
875 /// .expect("failed to execute process");
877 /// println!("status: {}", output.status);
878 /// io::stdout().write_all(&output.stdout).unwrap();
879 /// io::stderr().write_all(&output.stderr).unwrap();
881 /// assert!(output.status.success());
883 #[stable(feature = "process", since = "1.0.0")]
884 pub fn output(&mut self) -> io::Result<Output> {
886 .spawn(imp::Stdio::MakePipe, false)
887 .map(Child::from_inner)
888 .and_then(|p| p.wait_with_output())
891 /// Executes a command as a child process, waiting for it to finish and
892 /// collecting its status.
894 /// By default, stdin, stdout and stderr are inherited from the parent.
899 /// use std::process::Command;
901 /// let status = Command::new("/bin/cat")
904 /// .expect("failed to execute process");
906 /// println!("process finished with: {}", status);
908 /// assert!(status.success());
910 #[stable(feature = "process", since = "1.0.0")]
911 pub fn status(&mut self) -> io::Result<ExitStatus> {
913 .spawn(imp::Stdio::Inherit, true)
914 .map(Child::from_inner)
915 .and_then(|mut p| p.wait())
918 /// Returns the path to the program that was given to [`Command::new`].
923 /// # #![feature(command_access)]
924 /// use std::process::Command;
926 /// let cmd = Command::new("echo");
927 /// assert_eq!(cmd.get_program(), "echo");
929 #[unstable(feature = "command_access", issue = "44434")]
930 pub fn get_program(&self) -> &OsStr {
931 self.inner.get_program()
934 /// Returns an iterator of the arguments that will be passed to the program.
936 /// This does not include the path to the program as the first argument;
937 /// it only includes the arguments specified with [`Command::arg`] and
938 /// [`Command::args`].
943 /// # #![feature(command_access)]
944 /// use std::ffi::OsStr;
945 /// use std::process::Command;
947 /// let mut cmd = Command::new("echo");
948 /// cmd.arg("first").arg("second");
949 /// let args: Vec<&OsStr> = cmd.get_args().collect();
950 /// assert_eq!(args, &["first", "second"]);
952 #[unstable(feature = "command_access", issue = "44434")]
953 pub fn get_args(&self) -> CommandArgs<'_> {
954 CommandArgs { inner: self.inner.get_args() }
957 /// Returns an iterator of the environment variables that will be set when
958 /// the process is spawned.
960 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
961 /// value is the key, and the second is the value, which is [`None`] if
962 /// the environment variable is to be explicitly removed.
964 /// This only includes environment variables explicitly set with
965 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
966 /// does not include environment variables that will be inherited by the
972 /// # #![feature(command_access)]
973 /// use std::ffi::OsStr;
974 /// use std::process::Command;
976 /// let mut cmd = Command::new("ls");
977 /// cmd.env("TERM", "dumb").env_remove("TZ");
978 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
979 /// assert_eq!(envs, &[
980 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
981 /// (OsStr::new("TZ"), None)
984 #[unstable(feature = "command_access", issue = "44434")]
985 pub fn get_envs(&self) -> CommandEnvs<'_> {
986 self.inner.get_envs()
989 /// Returns the working directory for the child process.
991 /// This returns [`None`] if the working directory will not be changed.
996 /// # #![feature(command_access)]
997 /// use std::path::Path;
998 /// use std::process::Command;
1000 /// let mut cmd = Command::new("ls");
1001 /// assert_eq!(cmd.get_current_dir(), None);
1002 /// cmd.current_dir("/bin");
1003 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1005 #[unstable(feature = "command_access", issue = "44434")]
1006 pub fn get_current_dir(&self) -> Option<&Path> {
1007 self.inner.get_current_dir()
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl fmt::Debug for Command {
1013 /// Format the program and arguments of a Command for display. Any
1014 /// non-utf8 data is lossily converted using the utf8 replacement
1016 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1021 impl AsInner<imp::Command> for Command {
1022 fn as_inner(&self) -> &imp::Command {
1027 impl AsInnerMut<imp::Command> for Command {
1028 fn as_inner_mut(&mut self) -> &mut imp::Command {
1033 /// An iterator over the command arguments.
1035 /// This struct is created by [`Command::get_args`]. See its documentation for
1037 #[unstable(feature = "command_access", issue = "44434")]
1039 pub struct CommandArgs<'a> {
1040 inner: imp::CommandArgs<'a>,
1043 #[unstable(feature = "command_access", issue = "44434")]
1044 impl<'a> Iterator for CommandArgs<'a> {
1045 type Item = &'a OsStr;
1046 fn next(&mut self) -> Option<&'a OsStr> {
1049 fn size_hint(&self) -> (usize, Option<usize>) {
1050 self.inner.size_hint()
1054 #[unstable(feature = "command_access", issue = "44434")]
1055 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1056 fn len(&self) -> usize {
1059 fn is_empty(&self) -> bool {
1060 self.inner.is_empty()
1064 /// The output of a finished process.
1066 /// This is returned in a Result by either the [`output`] method of a
1067 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1070 /// [`output`]: Command::output
1071 /// [`wait_with_output`]: Child::wait_with_output
1072 #[derive(PartialEq, Eq, Clone)]
1073 #[stable(feature = "process", since = "1.0.0")]
1075 /// The status (exit code) of the process.
1076 #[stable(feature = "process", since = "1.0.0")]
1077 pub status: ExitStatus,
1078 /// The data that the process wrote to stdout.
1079 #[stable(feature = "process", since = "1.0.0")]
1080 pub stdout: Vec<u8>,
1081 /// The data that the process wrote to stderr.
1082 #[stable(feature = "process", since = "1.0.0")]
1083 pub stderr: Vec<u8>,
1086 // If either stderr or stdout are valid utf8 strings it prints the valid
1087 // strings, otherwise it prints the byte sequence instead
1088 #[stable(feature = "process_output_debug", since = "1.7.0")]
1089 impl fmt::Debug for Output {
1090 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1091 let stdout_utf8 = str::from_utf8(&self.stdout);
1092 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1094 Err(_) => &self.stdout,
1097 let stderr_utf8 = str::from_utf8(&self.stderr);
1098 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1100 Err(_) => &self.stderr,
1103 fmt.debug_struct("Output")
1104 .field("status", &self.status)
1105 .field("stdout", stdout_debug)
1106 .field("stderr", stderr_debug)
1111 /// Describes what to do with a standard I/O stream for a child process when
1112 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1114 /// [`stdin`]: Command::stdin
1115 /// [`stdout`]: Command::stdout
1116 /// [`stderr`]: Command::stderr
1117 #[stable(feature = "process", since = "1.0.0")]
1118 pub struct Stdio(imp::Stdio);
1121 /// A new pipe should be arranged to connect the parent and child processes.
1128 /// use std::process::{Command, Stdio};
1130 /// let output = Command::new("echo")
1131 /// .arg("Hello, world!")
1132 /// .stdout(Stdio::piped())
1134 /// .expect("Failed to execute command");
1136 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1137 /// // Nothing echoed to console
1143 /// use std::io::Write;
1144 /// use std::process::{Command, Stdio};
1146 /// let mut child = Command::new("rev")
1147 /// .stdin(Stdio::piped())
1148 /// .stdout(Stdio::piped())
1150 /// .expect("Failed to spawn child process");
1152 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1153 /// std::thread::spawn(move || {
1154 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1157 /// let output = child.wait_with_output().expect("Failed to read stdout");
1158 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1161 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1162 /// stdout and stderr at the same time may cause a deadlock.
1163 /// This is an issue when running any program that doesn't guarantee that it reads
1164 /// its entire stdin before writing more than a pipe buffer's worth of output.
1165 /// The size of a pipe buffer varies on different targets.
1167 #[stable(feature = "process", since = "1.0.0")]
1168 pub fn piped() -> Stdio {
1169 Stdio(imp::Stdio::MakePipe)
1172 /// The child inherits from the corresponding parent descriptor.
1179 /// use std::process::{Command, Stdio};
1181 /// let output = Command::new("echo")
1182 /// .arg("Hello, world!")
1183 /// .stdout(Stdio::inherit())
1185 /// .expect("Failed to execute command");
1187 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1188 /// // "Hello, world!" echoed to console
1194 /// use std::process::{Command, Stdio};
1195 /// use std::io::{self, Write};
1197 /// let output = Command::new("rev")
1198 /// .stdin(Stdio::inherit())
1199 /// .stdout(Stdio::piped())
1201 /// .expect("Failed to execute command");
1203 /// print!("You piped in the reverse of: ");
1204 /// io::stdout().write_all(&output.stdout).unwrap();
1206 #[stable(feature = "process", since = "1.0.0")]
1207 pub fn inherit() -> Stdio {
1208 Stdio(imp::Stdio::Inherit)
1211 /// This stream will be ignored. This is the equivalent of attaching the
1212 /// stream to `/dev/null`.
1219 /// use std::process::{Command, Stdio};
1221 /// let output = Command::new("echo")
1222 /// .arg("Hello, world!")
1223 /// .stdout(Stdio::null())
1225 /// .expect("Failed to execute command");
1227 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1228 /// // Nothing echoed to console
1234 /// use std::process::{Command, Stdio};
1236 /// let output = Command::new("rev")
1237 /// .stdin(Stdio::null())
1238 /// .stdout(Stdio::piped())
1240 /// .expect("Failed to execute command");
1242 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1243 /// // Ignores any piped-in input
1245 #[stable(feature = "process", since = "1.0.0")]
1246 pub fn null() -> Stdio {
1247 Stdio(imp::Stdio::Null)
1251 impl FromInner<imp::Stdio> for Stdio {
1252 fn from_inner(inner: imp::Stdio) -> Stdio {
1257 #[stable(feature = "std_debug", since = "1.16.0")]
1258 impl fmt::Debug for Stdio {
1259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1260 f.pad("Stdio { .. }")
1264 #[stable(feature = "stdio_from", since = "1.20.0")]
1265 impl From<ChildStdin> for Stdio {
1266 /// Converts a `ChildStdin` into a `Stdio`
1270 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1273 /// use std::process::{Command, Stdio};
1275 /// let reverse = Command::new("rev")
1276 /// .stdin(Stdio::piped())
1278 /// .expect("failed reverse command");
1280 /// let _echo = Command::new("echo")
1281 /// .arg("Hello, world!")
1282 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1284 /// .expect("failed echo command");
1286 /// // "!dlrow ,olleH" echoed to console
1288 fn from(child: ChildStdin) -> Stdio {
1289 Stdio::from_inner(child.into_inner().into())
1293 #[stable(feature = "stdio_from", since = "1.20.0")]
1294 impl From<ChildStdout> for Stdio {
1295 /// Converts a `ChildStdout` into a `Stdio`
1299 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1302 /// use std::process::{Command, Stdio};
1304 /// let hello = Command::new("echo")
1305 /// .arg("Hello, world!")
1306 /// .stdout(Stdio::piped())
1308 /// .expect("failed echo command");
1310 /// let reverse = Command::new("rev")
1311 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1313 /// .expect("failed reverse command");
1315 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1317 fn from(child: ChildStdout) -> Stdio {
1318 Stdio::from_inner(child.into_inner().into())
1322 #[stable(feature = "stdio_from", since = "1.20.0")]
1323 impl From<ChildStderr> for Stdio {
1324 /// Converts a `ChildStderr` into a `Stdio`
1329 /// use std::process::{Command, Stdio};
1331 /// let reverse = Command::new("rev")
1332 /// .arg("non_existing_file.txt")
1333 /// .stderr(Stdio::piped())
1335 /// .expect("failed reverse command");
1337 /// let cat = Command::new("cat")
1339 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1341 /// .expect("failed echo command");
1344 /// String::from_utf8_lossy(&cat.stdout),
1345 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1348 fn from(child: ChildStderr) -> Stdio {
1349 Stdio::from_inner(child.into_inner().into())
1353 #[stable(feature = "stdio_from", since = "1.20.0")]
1354 impl From<fs::File> for Stdio {
1355 /// Converts a `File` into a `Stdio`
1359 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1362 /// use std::fs::File;
1363 /// use std::process::Command;
1365 /// // With the `foo.txt` file containing `Hello, world!"
1366 /// let file = File::open("foo.txt").unwrap();
1368 /// let reverse = Command::new("rev")
1369 /// .stdin(file) // Implicit File conversion into a Stdio
1371 /// .expect("failed reverse command");
1373 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1375 fn from(file: fs::File) -> Stdio {
1376 Stdio::from_inner(file.into_inner().into())
1380 /// Describes the result of a process after it has terminated.
1382 /// This `struct` is used to represent the exit status or other termination of a child process.
1383 /// Child processes are created via the [`Command`] struct and their exit
1384 /// status is exposed through the [`status`] method, or the [`wait`] method
1385 /// of a [`Child`] process.
1387 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1388 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1390 /// For proper error reporting of failed processes, print the value of `ExitStatus` using its
1391 /// implementation of [`Display`](crate::fmt::Display).
1393 /// [`status`]: Command::status
1394 /// [`wait`]: Child::wait
1395 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1396 #[stable(feature = "process", since = "1.0.0")]
1397 pub struct ExitStatus(imp::ExitStatus);
1399 /// Allows extension traits within `std`.
1400 #[unstable(feature = "sealed", issue = "none")]
1401 impl crate::sealed::Sealed for ExitStatus {}
1404 /// Was termination successful? Signal termination is not considered a
1405 /// success, and success is defined as a zero exit status.
1410 /// use std::process::Command;
1412 /// let status = Command::new("mkdir")
1413 /// .arg("projects")
1415 /// .expect("failed to execute mkdir");
1417 /// if status.success() {
1418 /// println!("'projects/' directory created");
1420 /// println!("failed to create 'projects/' directory: {}", status);
1423 #[stable(feature = "process", since = "1.0.0")]
1424 pub fn success(&self) -> bool {
1428 /// Returns the exit code of the process, if any.
1430 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1431 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1432 /// bits, and that values that didn't come from a program's call to `exit` may be invented the
1433 /// runtime system (often, for example, 255, 254, 127 or 126).
1435 /// On Unix, this will return `None` if the process was terminated by a signal.
1436 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1437 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1442 /// use std::process::Command;
1444 /// let status = Command::new("mkdir")
1445 /// .arg("projects")
1447 /// .expect("failed to execute mkdir");
1449 /// match status.code() {
1450 /// Some(code) => println!("Exited with status code: {}", code),
1451 /// None => println!("Process terminated by signal")
1454 #[stable(feature = "process", since = "1.0.0")]
1455 pub fn code(&self) -> Option<i32> {
1460 impl AsInner<imp::ExitStatus> for ExitStatus {
1461 fn as_inner(&self) -> &imp::ExitStatus {
1466 impl FromInner<imp::ExitStatus> for ExitStatus {
1467 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1472 #[stable(feature = "process", since = "1.0.0")]
1473 impl fmt::Display for ExitStatus {
1474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1479 /// This type represents the status code a process can return to its
1480 /// parent under normal termination.
1482 /// Numeric values used in this type don't have portable meanings, and
1483 /// different platforms may mask different amounts of them.
1485 /// For the platform's canonical successful and unsuccessful codes, see
1486 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1488 /// [`SUCCESS`]: ExitCode::SUCCESS
1489 /// [`FAILURE`]: ExitCode::FAILURE
1491 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1492 /// it was ultimately cut from that RFC, and thus this type is more subject
1493 /// to change even than the usual unstable item churn.
1495 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1496 #[derive(Clone, Copy, Debug)]
1497 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1498 pub struct ExitCode(imp::ExitCode);
1500 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1502 /// The canonical ExitCode for successful termination on this platform.
1504 /// Note that a `()`-returning `main` implicitly results in a successful
1505 /// termination, so there's no need to return this from `main` unless
1506 /// you're also returning other possible codes.
1507 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1508 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1510 /// The canonical ExitCode for unsuccessful termination on this platform.
1512 /// If you're only returning this and `SUCCESS` from `main`, consider
1513 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1514 /// return the same codes (but will also `eprintln!` the error).
1515 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1516 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1520 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1521 /// error is returned.
1523 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1524 /// especially the [`Other`] kind might change to more specific kinds in the future.
1526 /// This is equivalent to sending a SIGKILL on Unix platforms.
1533 /// use std::process::Command;
1535 /// let mut command = Command::new("yes");
1536 /// if let Ok(mut child) = command.spawn() {
1537 /// child.kill().expect("command wasn't running");
1539 /// println!("yes command didn't start");
1543 /// [`ErrorKind`]: io::ErrorKind
1544 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1545 /// [`Other`]: io::ErrorKind::Other
1546 #[stable(feature = "process", since = "1.0.0")]
1547 pub fn kill(&mut self) -> io::Result<()> {
1551 /// Returns the OS-assigned process identifier associated with this child.
1558 /// use std::process::Command;
1560 /// let mut command = Command::new("ls");
1561 /// if let Ok(child) = command.spawn() {
1562 /// println!("Child's ID is {}", child.id());
1564 /// println!("ls command didn't start");
1567 #[stable(feature = "process_id", since = "1.3.0")]
1568 pub fn id(&self) -> u32 {
1572 /// Waits for the child to exit completely, returning the status that it
1573 /// exited with. This function will continue to have the same return value
1574 /// after it has been called at least once.
1576 /// The stdin handle to the child process, if any, will be closed
1577 /// before waiting. This helps avoid deadlock: it ensures that the
1578 /// child does not block waiting for input from the parent, while
1579 /// the parent waits for the child to exit.
1586 /// use std::process::Command;
1588 /// let mut command = Command::new("ls");
1589 /// if let Ok(mut child) = command.spawn() {
1590 /// child.wait().expect("command wasn't running");
1591 /// println!("Child has finished its execution!");
1593 /// println!("ls command didn't start");
1596 #[stable(feature = "process", since = "1.0.0")]
1597 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1598 drop(self.stdin.take());
1599 self.handle.wait().map(ExitStatus)
1602 /// Attempts to collect the exit status of the child if it has already
1605 /// This function will not block the calling thread and will only
1606 /// check to see if the child process has exited or not. If the child has
1607 /// exited then on Unix the process ID is reaped. This function is
1608 /// guaranteed to repeatedly return a successful exit status so long as the
1609 /// child has already exited.
1611 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1612 /// exit status is not available at this time then `Ok(None)` is returned.
1613 /// If an error occurs, then that error is returned.
1615 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1622 /// use std::process::Command;
1624 /// let mut child = Command::new("ls").spawn().unwrap();
1626 /// match child.try_wait() {
1627 /// Ok(Some(status)) => println!("exited with: {}", status),
1629 /// println!("status not ready yet, let's really wait");
1630 /// let res = child.wait();
1631 /// println!("result: {:?}", res);
1633 /// Err(e) => println!("error attempting to wait: {}", e),
1636 #[stable(feature = "process_try_wait", since = "1.18.0")]
1637 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1638 Ok(self.handle.try_wait()?.map(ExitStatus))
1641 /// Simultaneously waits for the child to exit and collect all remaining
1642 /// output on the stdout/stderr handles, returning an `Output`
1645 /// The stdin handle to the child process, if any, will be closed
1646 /// before waiting. This helps avoid deadlock: it ensures that the
1647 /// child does not block waiting for input from the parent, while
1648 /// the parent waits for the child to exit.
1650 /// By default, stdin, stdout and stderr are inherited from the parent.
1651 /// In order to capture the output into this `Result<Output>` it is
1652 /// necessary to create new pipes between parent and child. Use
1653 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1658 /// use std::process::{Command, Stdio};
1660 /// let child = Command::new("/bin/cat")
1661 /// .arg("file.txt")
1662 /// .stdout(Stdio::piped())
1664 /// .expect("failed to execute child");
1666 /// let output = child
1667 /// .wait_with_output()
1668 /// .expect("failed to wait on child");
1670 /// assert!(output.status.success());
1673 #[stable(feature = "process", since = "1.0.0")]
1674 pub fn wait_with_output(mut self) -> io::Result<Output> {
1675 drop(self.stdin.take());
1677 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1678 match (self.stdout.take(), self.stderr.take()) {
1680 (Some(mut out), None) => {
1681 let res = out.read_to_end(&mut stdout);
1684 (None, Some(mut err)) => {
1685 let res = err.read_to_end(&mut stderr);
1688 (Some(out), Some(err)) => {
1689 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1694 let status = self.wait()?;
1695 Ok(Output { status, stdout, stderr })
1699 /// Terminates the current process with the specified exit code.
1701 /// This function will never return and will immediately terminate the current
1702 /// process. The exit code is passed through to the underlying OS and will be
1703 /// available for consumption by another process.
1705 /// Note that because this function never returns, and that it terminates the
1706 /// process, no destructors on the current stack or any other thread's stack
1707 /// will be run. If a clean shutdown is needed it is recommended to only call
1708 /// this function at a known point where there are no more destructors left
1711 /// ## Platform-specific behavior
1713 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1714 /// will be visible to a parent process inspecting the exit code. On most
1715 /// Unix-like platforms, only the eight least-significant bits are considered.
1719 /// Due to this function’s behavior regarding destructors, a conventional way
1720 /// to use the function is to extract the actual computation to another
1721 /// function and compute the exit code from its return value:
1724 /// fn run_app() -> Result<(), ()> {
1725 /// // Application logic here
1730 /// std::process::exit(match run_app() {
1733 /// eprintln!("error: {:?}", err);
1740 /// Due to [platform-specific behavior], the exit code for this example will be
1741 /// `0` on Linux, but `256` on Windows:
1744 /// use std::process;
1746 /// process::exit(0x0100);
1749 /// [platform-specific behavior]: #platform-specific-behavior
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 pub fn exit(code: i32) -> ! {
1752 crate::sys_common::cleanup();
1753 crate::sys::os::exit(code)
1756 /// Terminates the process in an abnormal fashion.
1758 /// The function will never return and will immediately terminate the current
1759 /// process in a platform specific "abnormal" manner.
1761 /// Note that because this function never returns, and that it terminates the
1762 /// process, no destructors on the current stack or any other thread's stack
1765 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1766 /// the current thread's stack and calls all destructors.
1767 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1768 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1769 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1771 /// If a clean shutdown is needed it is recommended to only call
1772 /// this function at a known point where there are no more destructors left
1778 /// use std::process;
1781 /// println!("aborting");
1783 /// process::abort();
1785 /// // execution never gets here
1789 /// The `abort` function terminates the process, so the destructor will not
1790 /// get run on the example below:
1793 /// use std::process;
1797 /// impl Drop for HasDrop {
1798 /// fn drop(&mut self) {
1799 /// println!("This will never be printed!");
1804 /// let _x = HasDrop;
1805 /// process::abort();
1806 /// // the destructor implemented for HasDrop will never get run
1810 /// [panic hook]: crate::panic::set_hook
1811 #[stable(feature = "process_abort", since = "1.17.0")]
1813 pub fn abort() -> ! {
1814 crate::sys::abort_internal();
1817 /// Returns the OS-assigned process identifier associated with this process.
1824 /// use std::process;
1826 /// println!("My pid is {}", process::id());
1830 #[stable(feature = "getpid", since = "1.26.0")]
1831 pub fn id() -> u32 {
1832 crate::sys::os::getpid()
1835 /// A trait for implementing arbitrary return types in the `main` function.
1837 /// The C-main function only supports to return integers as return type.
1838 /// So, every type implementing the `Termination` trait has to be converted
1841 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1842 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1843 #[cfg_attr(not(test), lang = "termination")]
1844 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1845 #[rustc_on_unimplemented(
1846 message = "`main` has invalid return type `{Self}`",
1847 label = "`main` can only return types that implement `{Termination}`"
1849 pub trait Termination {
1850 /// Is called to get the representation of the value as status code.
1851 /// This status code is returned to the operating system.
1852 fn report(self) -> i32;
1855 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1856 impl Termination for () {
1858 fn report(self) -> i32 {
1859 ExitCode::SUCCESS.report()
1863 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1864 impl<E: fmt::Debug> Termination for Result<(), E> {
1865 fn report(self) -> i32 {
1867 Ok(()) => ().report(),
1868 Err(err) => Err::<!, _>(err).report(),
1873 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1874 impl Termination for ! {
1875 fn report(self) -> i32 {
1880 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1881 impl<E: fmt::Debug> Termination for Result<!, E> {
1882 fn report(self) -> i32 {
1883 let Err(err) = self;
1884 eprintln!("Error: {:?}", err);
1885 ExitCode::FAILURE.report()
1889 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1890 impl Termination for ExitCode {
1892 fn report(self) -> i32 {