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::convert::Infallible;
110 use crate::ffi::OsStr;
113 use crate::io::{self, IoSlice, IoSliceMut};
114 use crate::num::NonZeroI32;
115 use crate::path::Path;
117 use crate::sys::pipe::{read2, AnonPipe};
118 use crate::sys::process as imp;
119 #[stable(feature = "command_access", since = "1.57.0")]
120 pub use crate::sys_common::process::CommandEnvs;
121 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
123 /// Representation of a running or exited child process.
125 /// This structure is used to represent and manage child processes. A child
126 /// process is created via the [`Command`] struct, which configures the
127 /// spawning process and can itself be constructed using a builder-style
130 /// There is no implementation of [`Drop`] for child processes,
131 /// so if you do not ensure the `Child` has exited then it will continue to
132 /// run, even after the `Child` handle to the child process has gone out of
135 /// Calling [`wait`] (or other functions that wrap around it) will make
136 /// the parent process wait until the child has actually exited before
141 /// On some systems, calling [`wait`] or similar is necessary for the OS to
142 /// release resources. A process that terminated but has not been waited on is
143 /// still around as a "zombie". Leaving too many zombies around may exhaust
144 /// global resources (for example process IDs).
146 /// The standard library does *not* automatically wait on child processes (not
147 /// even if the `Child` is dropped), it is up to the application developer to do
148 /// so. As a consequence, dropping `Child` handles without waiting on them first
149 /// is not recommended in long-running applications.
154 /// use std::process::Command;
156 /// let mut child = Command::new("/bin/cat")
159 /// .expect("failed to execute child");
161 /// let ecode = child.wait()
162 /// .expect("failed to wait on child");
164 /// assert!(ecode.success());
167 /// [`wait`]: Child::wait
168 #[stable(feature = "process", since = "1.0.0")]
170 pub(crate) handle: imp::Process,
172 /// The handle for writing to the child's standard input (stdin), if it has
173 /// been captured. To avoid partially moving
174 /// the `child` and thus blocking yourself from calling
175 /// functions on `child` while using `stdin`,
176 /// you might find it helpful:
178 /// ```compile_fail,E0425
179 /// let stdin = child.stdin.take().unwrap();
181 #[stable(feature = "process", since = "1.0.0")]
182 pub stdin: Option<ChildStdin>,
184 /// The handle for reading from the child's standard output (stdout), if it
185 /// has been captured. You might find it helpful to do
187 /// ```compile_fail,E0425
188 /// let stdout = child.stdout.take().unwrap();
191 /// to avoid partially moving the `child` and thus blocking yourself from calling
192 /// functions on `child` while using `stdout`.
193 #[stable(feature = "process", since = "1.0.0")]
194 pub stdout: Option<ChildStdout>,
196 /// The handle for reading from the child's standard error (stderr), if it
197 /// has been captured. You might find it helpful to do
199 /// ```compile_fail,E0425
200 /// let stderr = child.stderr.take().unwrap();
203 /// to avoid partially moving the `child` and thus blocking yourself from calling
204 /// functions on `child` while using `stderr`.
205 #[stable(feature = "process", since = "1.0.0")]
206 pub stderr: Option<ChildStderr>,
209 /// Allows extension traits within `std`.
210 #[unstable(feature = "sealed", issue = "none")]
211 impl crate::sealed::Sealed for Child {}
213 impl AsInner<imp::Process> for Child {
214 fn as_inner(&self) -> &imp::Process {
219 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
220 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
223 stdin: io.stdin.map(ChildStdin::from_inner),
224 stdout: io.stdout.map(ChildStdout::from_inner),
225 stderr: io.stderr.map(ChildStderr::from_inner),
230 impl IntoInner<imp::Process> for Child {
231 fn into_inner(self) -> imp::Process {
236 #[stable(feature = "std_debug", since = "1.16.0")]
237 impl fmt::Debug for Child {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 f.debug_struct("Child")
240 .field("stdin", &self.stdin)
241 .field("stdout", &self.stdout)
242 .field("stderr", &self.stderr)
243 .finish_non_exhaustive()
247 /// A handle to a child process's standard input (stdin).
249 /// This struct is used in the [`stdin`] field on [`Child`].
251 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
252 /// file handle will be closed. If the child process was blocked on input prior
253 /// to being dropped, it will become unblocked after dropping.
255 /// [`stdin`]: Child::stdin
257 #[stable(feature = "process", since = "1.0.0")]
258 pub struct ChildStdin {
262 // In addition to the `impl`s here, `ChildStdin` also has `impl`s for
263 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
264 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
265 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
266 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
268 #[stable(feature = "process", since = "1.0.0")]
269 impl Write for ChildStdin {
270 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
274 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
275 (&*self).write_vectored(bufs)
278 fn is_write_vectored(&self) -> bool {
279 io::Write::is_write_vectored(&&*self)
282 fn flush(&mut self) -> io::Result<()> {
287 #[stable(feature = "write_mt", since = "1.48.0")]
288 impl Write for &ChildStdin {
289 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
290 self.inner.write(buf)
293 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
294 self.inner.write_vectored(bufs)
297 fn is_write_vectored(&self) -> bool {
298 self.inner.is_write_vectored()
301 fn flush(&mut self) -> io::Result<()> {
306 impl AsInner<AnonPipe> for ChildStdin {
307 fn as_inner(&self) -> &AnonPipe {
312 impl IntoInner<AnonPipe> for ChildStdin {
313 fn into_inner(self) -> AnonPipe {
318 impl FromInner<AnonPipe> for ChildStdin {
319 fn from_inner(pipe: AnonPipe) -> ChildStdin {
320 ChildStdin { inner: pipe }
324 #[stable(feature = "std_debug", since = "1.16.0")]
325 impl fmt::Debug for ChildStdin {
326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327 f.debug_struct("ChildStdin").finish_non_exhaustive()
331 /// A handle to a child process's standard output (stdout).
333 /// This struct is used in the [`stdout`] field on [`Child`].
335 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
336 /// underlying file handle will be closed.
338 /// [`stdout`]: Child::stdout
340 #[stable(feature = "process", since = "1.0.0")]
341 pub struct ChildStdout {
345 // In addition to the `impl`s here, `ChildStdout` also has `impl`s for
346 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
347 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
348 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
349 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
351 #[stable(feature = "process", since = "1.0.0")]
352 impl Read for ChildStdout {
353 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
357 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
358 self.inner.read_vectored(bufs)
362 fn is_read_vectored(&self) -> bool {
363 self.inner.is_read_vectored()
367 impl AsInner<AnonPipe> for ChildStdout {
368 fn as_inner(&self) -> &AnonPipe {
373 impl IntoInner<AnonPipe> for ChildStdout {
374 fn into_inner(self) -> AnonPipe {
379 impl FromInner<AnonPipe> for ChildStdout {
380 fn from_inner(pipe: AnonPipe) -> ChildStdout {
381 ChildStdout { inner: pipe }
385 #[stable(feature = "std_debug", since = "1.16.0")]
386 impl fmt::Debug for ChildStdout {
387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388 f.debug_struct("ChildStdout").finish_non_exhaustive()
392 /// A handle to a child process's stderr.
394 /// This struct is used in the [`stderr`] field on [`Child`].
396 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
397 /// underlying file handle will be closed.
399 /// [`stderr`]: Child::stderr
401 #[stable(feature = "process", since = "1.0.0")]
402 pub struct ChildStderr {
406 // In addition to the `impl`s here, `ChildStderr` also has `impl`s for
407 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
408 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
409 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
410 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
412 #[stable(feature = "process", since = "1.0.0")]
413 impl Read for ChildStderr {
414 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
418 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
419 self.inner.read_vectored(bufs)
423 fn is_read_vectored(&self) -> bool {
424 self.inner.is_read_vectored()
428 impl AsInner<AnonPipe> for ChildStderr {
429 fn as_inner(&self) -> &AnonPipe {
434 impl IntoInner<AnonPipe> for ChildStderr {
435 fn into_inner(self) -> AnonPipe {
440 impl FromInner<AnonPipe> for ChildStderr {
441 fn from_inner(pipe: AnonPipe) -> ChildStderr {
442 ChildStderr { inner: pipe }
446 #[stable(feature = "std_debug", since = "1.16.0")]
447 impl fmt::Debug for ChildStderr {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 f.debug_struct("ChildStderr").finish_non_exhaustive()
453 /// A process builder, providing fine-grained control
454 /// over how a new process should be spawned.
456 /// A default configuration can be
457 /// generated using `Command::new(program)`, where `program` gives a path to the
458 /// program to be executed. Additional builder methods allow the configuration
459 /// to be changed (for example, by adding arguments) prior to spawning:
462 /// use std::process::Command;
464 /// let output = if cfg!(target_os = "windows") {
465 /// Command::new("cmd")
466 /// .args(["/C", "echo hello"])
468 /// .expect("failed to execute process")
470 /// Command::new("sh")
472 /// .arg("echo hello")
474 /// .expect("failed to execute process")
477 /// let hello = output.stdout;
480 /// `Command` can be reused to spawn multiple processes. The builder methods
481 /// change the command without needing to immediately spawn the process.
484 /// use std::process::Command;
486 /// let mut echo_hello = Command::new("sh");
487 /// echo_hello.arg("-c")
488 /// .arg("echo hello");
489 /// let hello_1 = echo_hello.output().expect("failed to execute process");
490 /// let hello_2 = echo_hello.output().expect("failed to execute process");
493 /// Similarly, you can call builder methods after spawning a process and then
494 /// spawn a new process with the modified settings.
497 /// use std::process::Command;
499 /// let mut list_dir = Command::new("ls");
501 /// // Execute `ls` in the current directory of the program.
502 /// list_dir.status().expect("process failed to execute");
506 /// // Change `ls` to execute in the root directory.
507 /// list_dir.current_dir("/");
509 /// // And then execute `ls` again but in the root directory.
510 /// list_dir.status().expect("process failed to execute");
512 #[stable(feature = "process", since = "1.0.0")]
517 /// Allows extension traits within `std`.
518 #[unstable(feature = "sealed", issue = "none")]
519 impl crate::sealed::Sealed for Command {}
522 /// Constructs a new `Command` for launching the program at
523 /// path `program`, with the following default configuration:
525 /// * No arguments to the program
526 /// * Inherit the current process's environment
527 /// * Inherit the current process's working directory
528 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
530 /// Builder methods are provided to change these defaults and
531 /// otherwise configure the process.
533 /// If `program` is not an absolute path, the `PATH` will be searched in
534 /// an OS-defined way.
536 /// The search path to be used may be controlled by setting the
537 /// `PATH` environment variable on the Command,
538 /// but this has some implementation limitations on Windows
539 /// (see issue #37519).
546 /// use std::process::Command;
548 /// Command::new("sh")
550 /// .expect("sh command failed to start");
552 #[stable(feature = "process", since = "1.0.0")]
553 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
554 Command { inner: imp::Command::new(program.as_ref()) }
557 /// Adds an argument to pass to the program.
559 /// Only one argument can be passed per use. So instead of:
562 /// # std::process::Command::new("sh")
563 /// .arg("-C /path/to/repo")
570 /// # std::process::Command::new("sh")
572 /// .arg("/path/to/repo")
576 /// To pass multiple arguments see [`args`].
578 /// [`args`]: Command::args
580 /// Note that the argument is not passed through a shell, but given
581 /// literally to the program. This means that shell syntax like quotes,
582 /// escaped characters, word splitting, glob patterns, substitution, etc.
590 /// use std::process::Command;
592 /// Command::new("ls")
596 /// .expect("ls command failed to start");
598 #[stable(feature = "process", since = "1.0.0")]
599 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
600 self.inner.arg(arg.as_ref());
604 /// Adds multiple arguments to pass to the program.
606 /// To pass a single argument see [`arg`].
608 /// [`arg`]: Command::arg
610 /// Note that the arguments are not passed through a shell, but given
611 /// literally to the program. This means that shell syntax like quotes,
612 /// escaped characters, word splitting, glob patterns, substitution, etc.
620 /// use std::process::Command;
622 /// Command::new("ls")
623 /// .args(["-l", "-a"])
625 /// .expect("ls command failed to start");
627 #[stable(feature = "process", since = "1.0.0")]
628 pub fn args<I, S>(&mut self, args: I) -> &mut Command
630 I: IntoIterator<Item = S>,
634 self.arg(arg.as_ref());
639 /// Inserts or updates an environment variable mapping.
641 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
642 /// and case-sensitive on all other platforms.
649 /// use std::process::Command;
651 /// Command::new("ls")
652 /// .env("PATH", "/bin")
654 /// .expect("ls command failed to start");
656 #[stable(feature = "process", since = "1.0.0")]
657 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
662 self.inner.env_mut().set(key.as_ref(), val.as_ref());
666 /// Adds or updates multiple environment variable mappings.
673 /// use std::process::{Command, Stdio};
675 /// use std::collections::HashMap;
677 /// let filtered_env : HashMap<String, String> =
678 /// env::vars().filter(|&(ref k, _)|
679 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
682 /// Command::new("printenv")
683 /// .stdin(Stdio::null())
684 /// .stdout(Stdio::inherit())
686 /// .envs(&filtered_env)
688 /// .expect("printenv failed to start");
690 #[stable(feature = "command_envs", since = "1.19.0")]
691 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
693 I: IntoIterator<Item = (K, V)>,
697 for (ref key, ref val) in vars {
698 self.inner.env_mut().set(key.as_ref(), val.as_ref());
703 /// Removes an environment variable mapping.
710 /// use std::process::Command;
712 /// Command::new("ls")
713 /// .env_remove("PATH")
715 /// .expect("ls command failed to start");
717 #[stable(feature = "process", since = "1.0.0")]
718 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
719 self.inner.env_mut().remove(key.as_ref());
723 /// Clears the entire environment map for the child process.
730 /// use std::process::Command;
732 /// Command::new("ls")
735 /// .expect("ls command failed to start");
737 #[stable(feature = "process", since = "1.0.0")]
738 pub fn env_clear(&mut self) -> &mut Command {
739 self.inner.env_mut().clear();
743 /// Sets the working directory for the child process.
745 /// # Platform-specific behavior
747 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
748 /// whether it should be interpreted relative to the parent's working
749 /// directory or relative to `current_dir`. The behavior in this case is
750 /// platform specific and unstable, and it's recommended to use
751 /// [`canonicalize`] to get an absolute program path instead.
758 /// use std::process::Command;
760 /// Command::new("ls")
761 /// .current_dir("/bin")
763 /// .expect("ls command failed to start");
766 /// [`canonicalize`]: crate::fs::canonicalize
767 #[stable(feature = "process", since = "1.0.0")]
768 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
769 self.inner.cwd(dir.as_ref().as_ref());
773 /// Configuration for the child process's standard input (stdin) handle.
775 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
776 /// defaults to [`piped`] when used with `output`.
778 /// [`inherit`]: Stdio::inherit
779 /// [`piped`]: Stdio::piped
786 /// use std::process::{Command, Stdio};
788 /// Command::new("ls")
789 /// .stdin(Stdio::null())
791 /// .expect("ls command failed to start");
793 #[stable(feature = "process", since = "1.0.0")]
794 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
795 self.inner.stdin(cfg.into().0);
799 /// Configuration for the child process's standard output (stdout) handle.
801 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
802 /// defaults to [`piped`] when used with `output`.
804 /// [`inherit`]: Stdio::inherit
805 /// [`piped`]: Stdio::piped
812 /// use std::process::{Command, Stdio};
814 /// Command::new("ls")
815 /// .stdout(Stdio::null())
817 /// .expect("ls command failed to start");
819 #[stable(feature = "process", since = "1.0.0")]
820 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
821 self.inner.stdout(cfg.into().0);
825 /// Configuration for the child process's standard error (stderr) handle.
827 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
828 /// defaults to [`piped`] when used with `output`.
830 /// [`inherit`]: Stdio::inherit
831 /// [`piped`]: Stdio::piped
838 /// use std::process::{Command, Stdio};
840 /// Command::new("ls")
841 /// .stderr(Stdio::null())
843 /// .expect("ls command failed to start");
845 #[stable(feature = "process", since = "1.0.0")]
846 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
847 self.inner.stderr(cfg.into().0);
851 /// Executes the command as a child process, returning a handle to it.
853 /// By default, stdin, stdout and stderr are inherited from the parent.
860 /// use std::process::Command;
862 /// Command::new("ls")
864 /// .expect("ls command failed to start");
866 #[stable(feature = "process", since = "1.0.0")]
867 pub fn spawn(&mut self) -> io::Result<Child> {
868 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
871 /// Executes the command as a child process, waiting for it to finish and
872 /// collecting all of its output.
874 /// By default, stdout and stderr are captured (and used to provide the
875 /// resulting output). Stdin is not inherited from the parent and any
876 /// attempt by the child process to read from the stdin stream will result
877 /// in the stream immediately closing.
882 /// use std::process::Command;
883 /// use std::io::{self, Write};
884 /// let output = Command::new("/bin/cat")
887 /// .expect("failed to execute process");
889 /// println!("status: {}", output.status);
890 /// io::stdout().write_all(&output.stdout).unwrap();
891 /// io::stderr().write_all(&output.stderr).unwrap();
893 /// assert!(output.status.success());
895 #[stable(feature = "process", since = "1.0.0")]
896 pub fn output(&mut self) -> io::Result<Output> {
898 .spawn(imp::Stdio::MakePipe, false)
899 .map(Child::from_inner)
900 .and_then(|p| p.wait_with_output())
903 /// Executes a command as a child process, waiting for it to finish and
904 /// collecting its status.
906 /// By default, stdin, stdout and stderr are inherited from the parent.
911 /// use std::process::Command;
913 /// let status = Command::new("/bin/cat")
916 /// .expect("failed to execute process");
918 /// println!("process finished with: {}", status);
920 /// assert!(status.success());
922 #[stable(feature = "process", since = "1.0.0")]
923 pub fn status(&mut self) -> io::Result<ExitStatus> {
925 .spawn(imp::Stdio::Inherit, true)
926 .map(Child::from_inner)
927 .and_then(|mut p| p.wait())
930 /// Returns the path to the program that was given to [`Command::new`].
935 /// use std::process::Command;
937 /// let cmd = Command::new("echo");
938 /// assert_eq!(cmd.get_program(), "echo");
941 #[stable(feature = "command_access", since = "1.57.0")]
942 pub fn get_program(&self) -> &OsStr {
943 self.inner.get_program()
946 /// Returns an iterator of the arguments that will be passed to the program.
948 /// This does not include the path to the program as the first argument;
949 /// it only includes the arguments specified with [`Command::arg`] and
950 /// [`Command::args`].
955 /// use std::ffi::OsStr;
956 /// use std::process::Command;
958 /// let mut cmd = Command::new("echo");
959 /// cmd.arg("first").arg("second");
960 /// let args: Vec<&OsStr> = cmd.get_args().collect();
961 /// assert_eq!(args, &["first", "second"]);
963 #[stable(feature = "command_access", since = "1.57.0")]
964 pub fn get_args(&self) -> CommandArgs<'_> {
965 CommandArgs { inner: self.inner.get_args() }
968 /// Returns an iterator of the environment variables that will be set when
969 /// the process is spawned.
971 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
972 /// value is the key, and the second is the value, which is [`None`] if
973 /// the environment variable is to be explicitly removed.
975 /// This only includes environment variables explicitly set with
976 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
977 /// does not include environment variables that will be inherited by the
983 /// use std::ffi::OsStr;
984 /// use std::process::Command;
986 /// let mut cmd = Command::new("ls");
987 /// cmd.env("TERM", "dumb").env_remove("TZ");
988 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
989 /// assert_eq!(envs, &[
990 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
991 /// (OsStr::new("TZ"), None)
994 #[stable(feature = "command_access", since = "1.57.0")]
995 pub fn get_envs(&self) -> CommandEnvs<'_> {
996 self.inner.get_envs()
999 /// Returns the working directory for the child process.
1001 /// This returns [`None`] if the working directory will not be changed.
1006 /// use std::path::Path;
1007 /// use std::process::Command;
1009 /// let mut cmd = Command::new("ls");
1010 /// assert_eq!(cmd.get_current_dir(), None);
1011 /// cmd.current_dir("/bin");
1012 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1015 #[stable(feature = "command_access", since = "1.57.0")]
1016 pub fn get_current_dir(&self) -> Option<&Path> {
1017 self.inner.get_current_dir()
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl fmt::Debug for Command {
1023 /// Format the program and arguments of a Command for display. Any
1024 /// non-utf8 data is lossily converted using the utf8 replacement
1026 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1031 impl AsInner<imp::Command> for Command {
1032 fn as_inner(&self) -> &imp::Command {
1037 impl AsInnerMut<imp::Command> for Command {
1038 fn as_inner_mut(&mut self) -> &mut imp::Command {
1043 /// An iterator over the command arguments.
1045 /// This struct is created by [`Command::get_args`]. See its documentation for
1047 #[must_use = "iterators are lazy and do nothing unless consumed"]
1048 #[stable(feature = "command_access", since = "1.57.0")]
1050 pub struct CommandArgs<'a> {
1051 inner: imp::CommandArgs<'a>,
1054 #[stable(feature = "command_access", since = "1.57.0")]
1055 impl<'a> Iterator for CommandArgs<'a> {
1056 type Item = &'a OsStr;
1057 fn next(&mut self) -> Option<&'a OsStr> {
1060 fn size_hint(&self) -> (usize, Option<usize>) {
1061 self.inner.size_hint()
1065 #[stable(feature = "command_access", since = "1.57.0")]
1066 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1067 fn len(&self) -> usize {
1070 fn is_empty(&self) -> bool {
1071 self.inner.is_empty()
1075 /// The output of a finished process.
1077 /// This is returned in a Result by either the [`output`] method of a
1078 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1081 /// [`output`]: Command::output
1082 /// [`wait_with_output`]: Child::wait_with_output
1083 #[derive(PartialEq, Eq, Clone)]
1084 #[stable(feature = "process", since = "1.0.0")]
1086 /// The status (exit code) of the process.
1087 #[stable(feature = "process", since = "1.0.0")]
1088 pub status: ExitStatus,
1089 /// The data that the process wrote to stdout.
1090 #[stable(feature = "process", since = "1.0.0")]
1091 pub stdout: Vec<u8>,
1092 /// The data that the process wrote to stderr.
1093 #[stable(feature = "process", since = "1.0.0")]
1094 pub stderr: Vec<u8>,
1097 // If either stderr or stdout are valid utf8 strings it prints the valid
1098 // strings, otherwise it prints the byte sequence instead
1099 #[stable(feature = "process_output_debug", since = "1.7.0")]
1100 impl fmt::Debug for Output {
1101 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1102 let stdout_utf8 = str::from_utf8(&self.stdout);
1103 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1105 Err(_) => &self.stdout,
1108 let stderr_utf8 = str::from_utf8(&self.stderr);
1109 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1111 Err(_) => &self.stderr,
1114 fmt.debug_struct("Output")
1115 .field("status", &self.status)
1116 .field("stdout", stdout_debug)
1117 .field("stderr", stderr_debug)
1122 /// Describes what to do with a standard I/O stream for a child process when
1123 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1125 /// [`stdin`]: Command::stdin
1126 /// [`stdout`]: Command::stdout
1127 /// [`stderr`]: Command::stderr
1128 #[stable(feature = "process", since = "1.0.0")]
1129 pub struct Stdio(imp::Stdio);
1132 /// A new pipe should be arranged to connect the parent and child processes.
1139 /// use std::process::{Command, Stdio};
1141 /// let output = Command::new("echo")
1142 /// .arg("Hello, world!")
1143 /// .stdout(Stdio::piped())
1145 /// .expect("Failed to execute command");
1147 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1148 /// // Nothing echoed to console
1154 /// use std::io::Write;
1155 /// use std::process::{Command, Stdio};
1157 /// let mut child = Command::new("rev")
1158 /// .stdin(Stdio::piped())
1159 /// .stdout(Stdio::piped())
1161 /// .expect("Failed to spawn child process");
1163 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1164 /// std::thread::spawn(move || {
1165 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1168 /// let output = child.wait_with_output().expect("Failed to read stdout");
1169 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1172 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1173 /// stdout and stderr at the same time may cause a deadlock.
1174 /// This is an issue when running any program that doesn't guarantee that it reads
1175 /// its entire stdin before writing more than a pipe buffer's worth of output.
1176 /// The size of a pipe buffer varies on different targets.
1179 #[stable(feature = "process", since = "1.0.0")]
1180 pub fn piped() -> Stdio {
1181 Stdio(imp::Stdio::MakePipe)
1184 /// The child inherits from the corresponding parent descriptor.
1191 /// use std::process::{Command, Stdio};
1193 /// let output = Command::new("echo")
1194 /// .arg("Hello, world!")
1195 /// .stdout(Stdio::inherit())
1197 /// .expect("Failed to execute command");
1199 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1200 /// // "Hello, world!" echoed to console
1206 /// use std::process::{Command, Stdio};
1207 /// use std::io::{self, Write};
1209 /// let output = Command::new("rev")
1210 /// .stdin(Stdio::inherit())
1211 /// .stdout(Stdio::piped())
1213 /// .expect("Failed to execute command");
1215 /// print!("You piped in the reverse of: ");
1216 /// io::stdout().write_all(&output.stdout).unwrap();
1219 #[stable(feature = "process", since = "1.0.0")]
1220 pub fn inherit() -> Stdio {
1221 Stdio(imp::Stdio::Inherit)
1224 /// This stream will be ignored. This is the equivalent of attaching the
1225 /// stream to `/dev/null`.
1232 /// use std::process::{Command, Stdio};
1234 /// let output = Command::new("echo")
1235 /// .arg("Hello, world!")
1236 /// .stdout(Stdio::null())
1238 /// .expect("Failed to execute command");
1240 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1241 /// // Nothing echoed to console
1247 /// use std::process::{Command, Stdio};
1249 /// let output = Command::new("rev")
1250 /// .stdin(Stdio::null())
1251 /// .stdout(Stdio::piped())
1253 /// .expect("Failed to execute command");
1255 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1256 /// // Ignores any piped-in input
1259 #[stable(feature = "process", since = "1.0.0")]
1260 pub fn null() -> Stdio {
1261 Stdio(imp::Stdio::Null)
1265 impl FromInner<imp::Stdio> for Stdio {
1266 fn from_inner(inner: imp::Stdio) -> Stdio {
1271 #[stable(feature = "std_debug", since = "1.16.0")]
1272 impl fmt::Debug for Stdio {
1273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1274 f.debug_struct("Stdio").finish_non_exhaustive()
1278 #[stable(feature = "stdio_from", since = "1.20.0")]
1279 impl From<ChildStdin> for Stdio {
1280 /// Converts a [`ChildStdin`] into a [`Stdio`].
1284 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1287 /// use std::process::{Command, Stdio};
1289 /// let reverse = Command::new("rev")
1290 /// .stdin(Stdio::piped())
1292 /// .expect("failed reverse command");
1294 /// let _echo = Command::new("echo")
1295 /// .arg("Hello, world!")
1296 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1298 /// .expect("failed echo command");
1300 /// // "!dlrow ,olleH" echoed to console
1302 fn from(child: ChildStdin) -> Stdio {
1303 Stdio::from_inner(child.into_inner().into())
1307 #[stable(feature = "stdio_from", since = "1.20.0")]
1308 impl From<ChildStdout> for Stdio {
1309 /// Converts a [`ChildStdout`] into a [`Stdio`].
1313 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1316 /// use std::process::{Command, Stdio};
1318 /// let hello = Command::new("echo")
1319 /// .arg("Hello, world!")
1320 /// .stdout(Stdio::piped())
1322 /// .expect("failed echo command");
1324 /// let reverse = Command::new("rev")
1325 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1327 /// .expect("failed reverse command");
1329 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1331 fn from(child: ChildStdout) -> Stdio {
1332 Stdio::from_inner(child.into_inner().into())
1336 #[stable(feature = "stdio_from", since = "1.20.0")]
1337 impl From<ChildStderr> for Stdio {
1338 /// Converts a [`ChildStderr`] into a [`Stdio`].
1343 /// use std::process::{Command, Stdio};
1345 /// let reverse = Command::new("rev")
1346 /// .arg("non_existing_file.txt")
1347 /// .stderr(Stdio::piped())
1349 /// .expect("failed reverse command");
1351 /// let cat = Command::new("cat")
1353 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1355 /// .expect("failed echo command");
1358 /// String::from_utf8_lossy(&cat.stdout),
1359 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1362 fn from(child: ChildStderr) -> Stdio {
1363 Stdio::from_inner(child.into_inner().into())
1367 #[stable(feature = "stdio_from", since = "1.20.0")]
1368 impl From<fs::File> for Stdio {
1369 /// Converts a [`File`](fs::File) into a [`Stdio`].
1373 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1376 /// use std::fs::File;
1377 /// use std::process::Command;
1379 /// // With the `foo.txt` file containing `Hello, world!"
1380 /// let file = File::open("foo.txt").unwrap();
1382 /// let reverse = Command::new("rev")
1383 /// .stdin(file) // Implicit File conversion into a Stdio
1385 /// .expect("failed reverse command");
1387 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1389 fn from(file: fs::File) -> Stdio {
1390 Stdio::from_inner(file.into_inner().into())
1394 /// Describes the result of a process after it has terminated.
1396 /// This `struct` is used to represent the exit status or other termination of a child process.
1397 /// Child processes are created via the [`Command`] struct and their exit
1398 /// status is exposed through the [`status`] method, or the [`wait`] method
1399 /// of a [`Child`] process.
1401 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1402 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1404 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1405 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1407 /// [`status`]: Command::status
1408 /// [`wait`]: Child::wait
1410 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1411 // vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1412 // matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1413 // mean an underlying system call such as `_exit`.
1414 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1415 #[stable(feature = "process", since = "1.0.0")]
1416 pub struct ExitStatus(imp::ExitStatus);
1418 /// Allows extension traits within `std`.
1419 #[unstable(feature = "sealed", issue = "none")]
1420 impl crate::sealed::Sealed for ExitStatus {}
1423 /// Was termination successful? Returns a `Result`.
1428 /// #![feature(exit_status_error)]
1429 /// # if cfg!(unix) {
1430 /// use std::process::Command;
1432 /// let status = Command::new("ls")
1433 /// .arg("/dev/nonexistent")
1435 /// .expect("ls could not be executed");
1437 /// println!("ls: {}", status);
1438 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1439 /// # } // cfg!(unix)
1441 #[unstable(feature = "exit_status_error", issue = "84908")]
1442 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1443 self.0.exit_ok().map_err(ExitStatusError)
1446 /// Was termination successful? Signal termination is not considered a
1447 /// success, and success is defined as a zero exit status.
1452 /// use std::process::Command;
1454 /// let status = Command::new("mkdir")
1455 /// .arg("projects")
1457 /// .expect("failed to execute mkdir");
1459 /// if status.success() {
1460 /// println!("'projects/' directory created");
1462 /// println!("failed to create 'projects/' directory: {}", status);
1466 #[stable(feature = "process", since = "1.0.0")]
1467 pub fn success(&self) -> bool {
1468 self.0.exit_ok().is_ok()
1471 /// Returns the exit code of the process, if any.
1473 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1474 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1475 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1476 /// runtime system (often, for example, 255, 254, 127 or 126).
1478 /// On Unix, this will return `None` if the process was terminated by a signal.
1479 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1480 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1485 /// use std::process::Command;
1487 /// let status = Command::new("mkdir")
1488 /// .arg("projects")
1490 /// .expect("failed to execute mkdir");
1492 /// match status.code() {
1493 /// Some(code) => println!("Exited with status code: {}", code),
1494 /// None => println!("Process terminated by signal")
1498 #[stable(feature = "process", since = "1.0.0")]
1499 pub fn code(&self) -> Option<i32> {
1504 impl AsInner<imp::ExitStatus> for ExitStatus {
1505 fn as_inner(&self) -> &imp::ExitStatus {
1510 impl FromInner<imp::ExitStatus> for ExitStatus {
1511 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1516 #[stable(feature = "process", since = "1.0.0")]
1517 impl fmt::Display for ExitStatus {
1518 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1523 /// Allows extension traits within `std`.
1524 #[unstable(feature = "sealed", issue = "none")]
1525 impl crate::sealed::Sealed for ExitStatusError {}
1527 /// Describes the result of a process after it has failed
1529 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1534 /// #![feature(exit_status_error)]
1535 /// # if cfg!(unix) {
1536 /// use std::process::{Command, ExitStatusError};
1538 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1539 /// Command::new(cmd).status().unwrap().exit_ok()?;
1543 /// run("true").unwrap();
1544 /// run("false").unwrap_err();
1545 /// # } // cfg!(unix)
1547 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1548 #[unstable(feature = "exit_status_error", issue = "84908")]
1549 // The definition of imp::ExitStatusError should ideally be such that
1550 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1551 pub struct ExitStatusError(imp::ExitStatusError);
1553 #[unstable(feature = "exit_status_error", issue = "84908")]
1554 impl ExitStatusError {
1555 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1557 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1558 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1559 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1560 /// runtime system (often, for example, 255, 254, 127 or 126).
1562 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1563 /// handle such situations specially, consider using methods from
1564 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1566 /// If the process finished by calling `exit` with a nonzero value, this will return
1567 /// that exit status.
1569 /// If the error was something else, it will return `None`.
1571 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1572 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1577 /// #![feature(exit_status_error)]
1578 /// # #[cfg(unix)] {
1579 /// use std::process::Command;
1581 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1582 /// assert_eq!(bad.code(), Some(1));
1583 /// # } // #[cfg(unix)]
1586 pub fn code(&self) -> Option<i32> {
1587 self.code_nonzero().map(Into::into)
1590 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1592 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1594 /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1595 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1596 /// a type-level guarantee of nonzeroness.
1601 /// #![feature(exit_status_error)]
1602 /// # if cfg!(unix) {
1603 /// use std::num::NonZeroI32;
1604 /// use std::process::Command;
1606 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1607 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1608 /// # } // cfg!(unix)
1611 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1615 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1617 pub fn into_status(&self) -> ExitStatus {
1618 ExitStatus(self.0.into())
1622 #[unstable(feature = "exit_status_error", issue = "84908")]
1623 impl Into<ExitStatus> for ExitStatusError {
1624 fn into(self) -> ExitStatus {
1625 ExitStatus(self.0.into())
1629 #[unstable(feature = "exit_status_error", issue = "84908")]
1630 impl fmt::Display for ExitStatusError {
1631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1632 write!(f, "process exited unsuccessfully: {}", self.into_status())
1636 #[unstable(feature = "exit_status_error", issue = "84908")]
1637 impl crate::error::Error for ExitStatusError {}
1639 /// This type represents the status code a process can return to its
1640 /// parent under normal termination.
1642 /// Numeric values used in this type don't have portable meanings, and
1643 /// different platforms may mask different amounts of them.
1645 /// For the platform's canonical successful and unsuccessful codes, see
1646 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1648 /// [`SUCCESS`]: ExitCode::SUCCESS
1649 /// [`FAILURE`]: ExitCode::FAILURE
1651 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1652 /// it was ultimately cut from that RFC, and thus this type is more subject
1653 /// to change even than the usual unstable item churn.
1655 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1656 #[derive(Clone, Copy, Debug)]
1657 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1658 pub struct ExitCode(imp::ExitCode);
1660 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1662 /// The canonical ExitCode for successful termination on this platform.
1664 /// Note that a `()`-returning `main` implicitly results in a successful
1665 /// termination, so there's no need to return this from `main` unless
1666 /// you're also returning other possible codes.
1667 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1668 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1670 /// The canonical ExitCode for unsuccessful termination on this platform.
1672 /// If you're only returning this and `SUCCESS` from `main`, consider
1673 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1674 /// return the same codes (but will also `eprintln!` the error).
1675 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1676 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1680 // This should not be stabilized when stabilizing ExitCode, we don't know that i32 will serve
1681 // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
1682 // likely want to isolate users anything that could restrict the platform specific
1683 // representation of an ExitCode
1685 // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
1686 /// Convert an ExitCode into an i32
1687 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1689 pub fn to_i32(self) -> i32 {
1694 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1695 impl From<u8> for ExitCode {
1696 /// Construct an exit code from an arbitrary u8 value.
1697 fn from(code: u8) -> Self {
1698 ExitCode(imp::ExitCode::from(code))
1703 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1704 /// error is returned.
1706 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1708 /// This is equivalent to sending a SIGKILL on Unix platforms.
1715 /// use std::process::Command;
1717 /// let mut command = Command::new("yes");
1718 /// if let Ok(mut child) = command.spawn() {
1719 /// child.kill().expect("command wasn't running");
1721 /// println!("yes command didn't start");
1725 /// [`ErrorKind`]: io::ErrorKind
1726 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1727 #[stable(feature = "process", since = "1.0.0")]
1728 pub fn kill(&mut self) -> io::Result<()> {
1732 /// Returns the OS-assigned process identifier associated with this child.
1739 /// use std::process::Command;
1741 /// let mut command = Command::new("ls");
1742 /// if let Ok(child) = command.spawn() {
1743 /// println!("Child's ID is {}", child.id());
1745 /// println!("ls command didn't start");
1749 #[stable(feature = "process_id", since = "1.3.0")]
1750 pub fn id(&self) -> u32 {
1754 /// Waits for the child to exit completely, returning the status that it
1755 /// exited with. This function will continue to have the same return value
1756 /// after it has been called at least once.
1758 /// The stdin handle to the child process, if any, will be closed
1759 /// before waiting. This helps avoid deadlock: it ensures that the
1760 /// child does not block waiting for input from the parent, while
1761 /// the parent waits for the child to exit.
1768 /// use std::process::Command;
1770 /// let mut command = Command::new("ls");
1771 /// if let Ok(mut child) = command.spawn() {
1772 /// child.wait().expect("command wasn't running");
1773 /// println!("Child has finished its execution!");
1775 /// println!("ls command didn't start");
1778 #[stable(feature = "process", since = "1.0.0")]
1779 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1780 drop(self.stdin.take());
1781 self.handle.wait().map(ExitStatus)
1784 /// Attempts to collect the exit status of the child if it has already
1787 /// This function will not block the calling thread and will only
1788 /// check to see if the child process has exited or not. If the child has
1789 /// exited then on Unix the process ID is reaped. This function is
1790 /// guaranteed to repeatedly return a successful exit status so long as the
1791 /// child has already exited.
1793 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1794 /// exit status is not available at this time then `Ok(None)` is returned.
1795 /// If an error occurs, then that error is returned.
1797 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1804 /// use std::process::Command;
1806 /// let mut child = Command::new("ls").spawn().unwrap();
1808 /// match child.try_wait() {
1809 /// Ok(Some(status)) => println!("exited with: {}", status),
1811 /// println!("status not ready yet, let's really wait");
1812 /// let res = child.wait();
1813 /// println!("result: {:?}", res);
1815 /// Err(e) => println!("error attempting to wait: {}", e),
1818 #[stable(feature = "process_try_wait", since = "1.18.0")]
1819 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1820 Ok(self.handle.try_wait()?.map(ExitStatus))
1823 /// Simultaneously waits for the child to exit and collect all remaining
1824 /// output on the stdout/stderr handles, returning an `Output`
1827 /// The stdin handle to the child process, if any, will be closed
1828 /// before waiting. This helps avoid deadlock: it ensures that the
1829 /// child does not block waiting for input from the parent, while
1830 /// the parent waits for the child to exit.
1832 /// By default, stdin, stdout and stderr are inherited from the parent.
1833 /// In order to capture the output into this `Result<Output>` it is
1834 /// necessary to create new pipes between parent and child. Use
1835 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1840 /// use std::process::{Command, Stdio};
1842 /// let child = Command::new("/bin/cat")
1843 /// .arg("file.txt")
1844 /// .stdout(Stdio::piped())
1846 /// .expect("failed to execute child");
1848 /// let output = child
1849 /// .wait_with_output()
1850 /// .expect("failed to wait on child");
1852 /// assert!(output.status.success());
1855 #[stable(feature = "process", since = "1.0.0")]
1856 pub fn wait_with_output(mut self) -> io::Result<Output> {
1857 drop(self.stdin.take());
1859 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1860 match (self.stdout.take(), self.stderr.take()) {
1862 (Some(mut out), None) => {
1863 let res = out.read_to_end(&mut stdout);
1866 (None, Some(mut err)) => {
1867 let res = err.read_to_end(&mut stderr);
1870 (Some(out), Some(err)) => {
1871 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1876 let status = self.wait()?;
1877 Ok(Output { status, stdout, stderr })
1881 /// Terminates the current process with the specified exit code.
1883 /// This function will never return and will immediately terminate the current
1884 /// process. The exit code is passed through to the underlying OS and will be
1885 /// available for consumption by another process.
1887 /// Note that because this function never returns, and that it terminates the
1888 /// process, no destructors on the current stack or any other thread's stack
1889 /// will be run. If a clean shutdown is needed it is recommended to only call
1890 /// this function at a known point where there are no more destructors left
1893 /// ## Platform-specific behavior
1895 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1896 /// will be visible to a parent process inspecting the exit code. On most
1897 /// Unix-like platforms, only the eight least-significant bits are considered.
1901 /// Due to this function’s behavior regarding destructors, a conventional way
1902 /// to use the function is to extract the actual computation to another
1903 /// function and compute the exit code from its return value:
1906 /// fn run_app() -> Result<(), ()> {
1907 /// // Application logic here
1912 /// std::process::exit(match run_app() {
1915 /// eprintln!("error: {:?}", err);
1922 /// Due to [platform-specific behavior], the exit code for this example will be
1923 /// `0` on Linux, but `256` on Windows:
1926 /// use std::process;
1928 /// process::exit(0x0100);
1931 /// [platform-specific behavior]: #platform-specific-behavior
1932 #[stable(feature = "rust1", since = "1.0.0")]
1933 pub fn exit(code: i32) -> ! {
1934 crate::rt::cleanup();
1935 crate::sys::os::exit(code)
1938 /// Terminates the process in an abnormal fashion.
1940 /// The function will never return and will immediately terminate the current
1941 /// process in a platform specific "abnormal" manner.
1943 /// Note that because this function never returns, and that it terminates the
1944 /// process, no destructors on the current stack or any other thread's stack
1947 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
1948 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
1950 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1951 /// the current thread's stack and calls all destructors.
1952 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1953 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1954 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1956 /// If a clean shutdown is needed it is recommended to only call
1957 /// this function at a known point where there are no more destructors left
1960 /// The process's termination will be similar to that from the C `abort()`
1961 /// function. On Unix, the process will terminate with signal `SIGABRT`, which
1962 /// typically means that the shell prints "Aborted".
1967 /// use std::process;
1970 /// println!("aborting");
1972 /// process::abort();
1974 /// // execution never gets here
1978 /// The `abort` function terminates the process, so the destructor will not
1979 /// get run on the example below:
1982 /// use std::process;
1986 /// impl Drop for HasDrop {
1987 /// fn drop(&mut self) {
1988 /// println!("This will never be printed!");
1993 /// let _x = HasDrop;
1994 /// process::abort();
1995 /// // the destructor implemented for HasDrop will never get run
1999 /// [panic hook]: crate::panic::set_hook
2000 #[stable(feature = "process_abort", since = "1.17.0")]
2002 pub fn abort() -> ! {
2003 crate::sys::abort_internal();
2006 /// Returns the OS-assigned process identifier associated with this process.
2013 /// use std::process;
2015 /// println!("My pid is {}", process::id());
2020 #[stable(feature = "getpid", since = "1.26.0")]
2021 pub fn id() -> u32 {
2022 crate::sys::os::getpid()
2025 /// A trait for implementing arbitrary return types in the `main` function.
2027 /// The C-main function only supports to return integers as return type.
2028 /// So, every type implementing the `Termination` trait has to be converted
2031 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2032 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2033 #[cfg_attr(not(test), lang = "termination")]
2034 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2035 #[rustc_on_unimplemented(
2036 message = "`main` has invalid return type `{Self}`",
2037 label = "`main` can only return types that implement `{Termination}`"
2039 pub trait Termination {
2040 /// Is called to get the representation of the value as status code.
2041 /// This status code is returned to the operating system.
2042 fn report(self) -> ExitCode;
2045 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2046 impl Termination for () {
2048 fn report(self) -> ExitCode {
2049 ExitCode::SUCCESS.report()
2053 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2054 impl<E: fmt::Debug> Termination for Result<(), E> {
2055 fn report(self) -> ExitCode {
2057 Ok(()) => ().report(),
2058 Err(err) => Err::<!, _>(err).report(),
2063 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2064 impl Termination for ! {
2065 fn report(self) -> ExitCode {
2070 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2071 impl<E: fmt::Debug> Termination for Result<!, E> {
2072 fn report(self) -> ExitCode {
2073 let Err(err) = self;
2074 eprintln!("Error: {:?}", err);
2075 ExitCode::FAILURE.report()
2079 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2080 impl<E: fmt::Debug> Termination for Result<Infallible, E> {
2081 fn report(self) -> ExitCode {
2082 let Err(err) = self;
2083 Err::<!, _>(err).report()
2087 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2088 impl Termination for ExitCode {
2090 fn report(self) -> ExitCode {