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, Initializer, 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 unsafe fn initializer(&self) -> Initializer {
368 // SAFETY: Read is guaranteed to work on uninitialized memory
369 unsafe { Initializer::nop() }
373 impl AsInner<AnonPipe> for ChildStdout {
374 fn as_inner(&self) -> &AnonPipe {
379 impl IntoInner<AnonPipe> for ChildStdout {
380 fn into_inner(self) -> AnonPipe {
385 impl FromInner<AnonPipe> for ChildStdout {
386 fn from_inner(pipe: AnonPipe) -> ChildStdout {
387 ChildStdout { inner: pipe }
391 #[stable(feature = "std_debug", since = "1.16.0")]
392 impl fmt::Debug for ChildStdout {
393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 f.debug_struct("ChildStdout").finish_non_exhaustive()
398 /// A handle to a child process's stderr.
400 /// This struct is used in the [`stderr`] field on [`Child`].
402 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
403 /// underlying file handle will be closed.
405 /// [`stderr`]: Child::stderr
407 #[stable(feature = "process", since = "1.0.0")]
408 pub struct ChildStderr {
412 // In addition to the `impl`s here, `ChildStderr` also has `impl`s for
413 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
414 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
415 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
416 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
418 #[stable(feature = "process", since = "1.0.0")]
419 impl Read for ChildStderr {
420 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
424 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
425 self.inner.read_vectored(bufs)
429 fn is_read_vectored(&self) -> bool {
430 self.inner.is_read_vectored()
434 unsafe fn initializer(&self) -> Initializer {
435 // SAFETY: Read is guaranteed to work on uninitialized memory
436 unsafe { Initializer::nop() }
440 impl AsInner<AnonPipe> for ChildStderr {
441 fn as_inner(&self) -> &AnonPipe {
446 impl IntoInner<AnonPipe> for ChildStderr {
447 fn into_inner(self) -> AnonPipe {
452 impl FromInner<AnonPipe> for ChildStderr {
453 fn from_inner(pipe: AnonPipe) -> ChildStderr {
454 ChildStderr { inner: pipe }
458 #[stable(feature = "std_debug", since = "1.16.0")]
459 impl fmt::Debug for ChildStderr {
460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461 f.debug_struct("ChildStderr").finish_non_exhaustive()
465 /// A process builder, providing fine-grained control
466 /// over how a new process should be spawned.
468 /// A default configuration can be
469 /// generated using `Command::new(program)`, where `program` gives a path to the
470 /// program to be executed. Additional builder methods allow the configuration
471 /// to be changed (for example, by adding arguments) prior to spawning:
474 /// use std::process::Command;
476 /// let output = if cfg!(target_os = "windows") {
477 /// Command::new("cmd")
478 /// .args(["/C", "echo hello"])
480 /// .expect("failed to execute process")
482 /// Command::new("sh")
484 /// .arg("echo hello")
486 /// .expect("failed to execute process")
489 /// let hello = output.stdout;
492 /// `Command` can be reused to spawn multiple processes. The builder methods
493 /// change the command without needing to immediately spawn the process.
496 /// use std::process::Command;
498 /// let mut echo_hello = Command::new("sh");
499 /// echo_hello.arg("-c")
500 /// .arg("echo hello");
501 /// let hello_1 = echo_hello.output().expect("failed to execute process");
502 /// let hello_2 = echo_hello.output().expect("failed to execute process");
505 /// Similarly, you can call builder methods after spawning a process and then
506 /// spawn a new process with the modified settings.
509 /// use std::process::Command;
511 /// let mut list_dir = Command::new("ls");
513 /// // Execute `ls` in the current directory of the program.
514 /// list_dir.status().expect("process failed to execute");
518 /// // Change `ls` to execute in the root directory.
519 /// list_dir.current_dir("/");
521 /// // And then execute `ls` again but in the root directory.
522 /// list_dir.status().expect("process failed to execute");
524 #[stable(feature = "process", since = "1.0.0")]
529 /// Allows extension traits within `std`.
530 #[unstable(feature = "sealed", issue = "none")]
531 impl crate::sealed::Sealed for Command {}
534 /// Constructs a new `Command` for launching the program at
535 /// path `program`, with the following default configuration:
537 /// * No arguments to the program
538 /// * Inherit the current process's environment
539 /// * Inherit the current process's working directory
540 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
542 /// Builder methods are provided to change these defaults and
543 /// otherwise configure the process.
545 /// If `program` is not an absolute path, the `PATH` will be searched in
546 /// an OS-defined way.
548 /// The search path to be used may be controlled by setting the
549 /// `PATH` environment variable on the Command,
550 /// but this has some implementation limitations on Windows
551 /// (see issue #37519).
558 /// use std::process::Command;
560 /// Command::new("sh")
562 /// .expect("sh command failed to start");
564 #[stable(feature = "process", since = "1.0.0")]
565 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
566 Command { inner: imp::Command::new(program.as_ref()) }
569 /// Adds an argument to pass to the program.
571 /// Only one argument can be passed per use. So instead of:
574 /// # std::process::Command::new("sh")
575 /// .arg("-C /path/to/repo")
582 /// # std::process::Command::new("sh")
584 /// .arg("/path/to/repo")
588 /// To pass multiple arguments see [`args`].
590 /// [`args`]: Command::args
592 /// Note that the argument is not passed through a shell, but given
593 /// literally to the program. This means that shell syntax like quotes,
594 /// escaped characters, word splitting, glob patterns, substitution, etc.
602 /// use std::process::Command;
604 /// Command::new("ls")
608 /// .expect("ls command failed to start");
610 #[stable(feature = "process", since = "1.0.0")]
611 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
612 self.inner.arg(arg.as_ref());
616 /// Adds multiple arguments to pass to the program.
618 /// To pass a single argument see [`arg`].
620 /// [`arg`]: Command::arg
622 /// Note that the arguments are not passed through a shell, but given
623 /// literally to the program. This means that shell syntax like quotes,
624 /// escaped characters, word splitting, glob patterns, substitution, etc.
632 /// use std::process::Command;
634 /// Command::new("ls")
635 /// .args(["-l", "-a"])
637 /// .expect("ls command failed to start");
639 #[stable(feature = "process", since = "1.0.0")]
640 pub fn args<I, S>(&mut self, args: I) -> &mut Command
642 I: IntoIterator<Item = S>,
646 self.arg(arg.as_ref());
651 /// Inserts or updates an environment variable mapping.
653 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
654 /// and case-sensitive on all other platforms.
661 /// use std::process::Command;
663 /// Command::new("ls")
664 /// .env("PATH", "/bin")
666 /// .expect("ls command failed to start");
668 #[stable(feature = "process", since = "1.0.0")]
669 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
674 self.inner.env_mut().set(key.as_ref(), val.as_ref());
678 /// Adds or updates multiple environment variable mappings.
685 /// use std::process::{Command, Stdio};
687 /// use std::collections::HashMap;
689 /// let filtered_env : HashMap<String, String> =
690 /// env::vars().filter(|&(ref k, _)|
691 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
694 /// Command::new("printenv")
695 /// .stdin(Stdio::null())
696 /// .stdout(Stdio::inherit())
698 /// .envs(&filtered_env)
700 /// .expect("printenv failed to start");
702 #[stable(feature = "command_envs", since = "1.19.0")]
703 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
705 I: IntoIterator<Item = (K, V)>,
709 for (ref key, ref val) in vars {
710 self.inner.env_mut().set(key.as_ref(), val.as_ref());
715 /// Removes an environment variable mapping.
722 /// use std::process::Command;
724 /// Command::new("ls")
725 /// .env_remove("PATH")
727 /// .expect("ls command failed to start");
729 #[stable(feature = "process", since = "1.0.0")]
730 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
731 self.inner.env_mut().remove(key.as_ref());
735 /// Clears the entire environment map for the child process.
742 /// use std::process::Command;
744 /// Command::new("ls")
747 /// .expect("ls command failed to start");
749 #[stable(feature = "process", since = "1.0.0")]
750 pub fn env_clear(&mut self) -> &mut Command {
751 self.inner.env_mut().clear();
755 /// Sets the working directory for the child process.
757 /// # Platform-specific behavior
759 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
760 /// whether it should be interpreted relative to the parent's working
761 /// directory or relative to `current_dir`. The behavior in this case is
762 /// platform specific and unstable, and it's recommended to use
763 /// [`canonicalize`] to get an absolute program path instead.
770 /// use std::process::Command;
772 /// Command::new("ls")
773 /// .current_dir("/bin")
775 /// .expect("ls command failed to start");
778 /// [`canonicalize`]: crate::fs::canonicalize
779 #[stable(feature = "process", since = "1.0.0")]
780 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
781 self.inner.cwd(dir.as_ref().as_ref());
785 /// Configuration for the child process's standard input (stdin) handle.
787 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
788 /// defaults to [`piped`] when used with `output`.
790 /// [`inherit`]: Stdio::inherit
791 /// [`piped`]: Stdio::piped
798 /// use std::process::{Command, Stdio};
800 /// Command::new("ls")
801 /// .stdin(Stdio::null())
803 /// .expect("ls command failed to start");
805 #[stable(feature = "process", since = "1.0.0")]
806 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
807 self.inner.stdin(cfg.into().0);
811 /// Configuration for the child process's standard output (stdout) handle.
813 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
814 /// defaults to [`piped`] when used with `output`.
816 /// [`inherit`]: Stdio::inherit
817 /// [`piped`]: Stdio::piped
824 /// use std::process::{Command, Stdio};
826 /// Command::new("ls")
827 /// .stdout(Stdio::null())
829 /// .expect("ls command failed to start");
831 #[stable(feature = "process", since = "1.0.0")]
832 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
833 self.inner.stdout(cfg.into().0);
837 /// Configuration for the child process's standard error (stderr) handle.
839 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
840 /// defaults to [`piped`] when used with `output`.
842 /// [`inherit`]: Stdio::inherit
843 /// [`piped`]: Stdio::piped
850 /// use std::process::{Command, Stdio};
852 /// Command::new("ls")
853 /// .stderr(Stdio::null())
855 /// .expect("ls command failed to start");
857 #[stable(feature = "process", since = "1.0.0")]
858 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
859 self.inner.stderr(cfg.into().0);
863 /// Executes the command as a child process, returning a handle to it.
865 /// By default, stdin, stdout and stderr are inherited from the parent.
872 /// use std::process::Command;
874 /// Command::new("ls")
876 /// .expect("ls command failed to start");
878 #[stable(feature = "process", since = "1.0.0")]
879 pub fn spawn(&mut self) -> io::Result<Child> {
880 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
883 /// Executes the command as a child process, waiting for it to finish and
884 /// collecting all of its output.
886 /// By default, stdout and stderr are captured (and used to provide the
887 /// resulting output). Stdin is not inherited from the parent and any
888 /// attempt by the child process to read from the stdin stream will result
889 /// in the stream immediately closing.
894 /// use std::process::Command;
895 /// use std::io::{self, Write};
896 /// let output = Command::new("/bin/cat")
899 /// .expect("failed to execute process");
901 /// println!("status: {}", output.status);
902 /// io::stdout().write_all(&output.stdout).unwrap();
903 /// io::stderr().write_all(&output.stderr).unwrap();
905 /// assert!(output.status.success());
907 #[stable(feature = "process", since = "1.0.0")]
908 pub fn output(&mut self) -> io::Result<Output> {
910 .spawn(imp::Stdio::MakePipe, false)
911 .map(Child::from_inner)
912 .and_then(|p| p.wait_with_output())
915 /// Executes a command as a child process, waiting for it to finish and
916 /// collecting its status.
918 /// By default, stdin, stdout and stderr are inherited from the parent.
923 /// use std::process::Command;
925 /// let status = Command::new("/bin/cat")
928 /// .expect("failed to execute process");
930 /// println!("process finished with: {}", status);
932 /// assert!(status.success());
934 #[stable(feature = "process", since = "1.0.0")]
935 pub fn status(&mut self) -> io::Result<ExitStatus> {
937 .spawn(imp::Stdio::Inherit, true)
938 .map(Child::from_inner)
939 .and_then(|mut p| p.wait())
942 /// Returns the path to the program that was given to [`Command::new`].
947 /// use std::process::Command;
949 /// let cmd = Command::new("echo");
950 /// assert_eq!(cmd.get_program(), "echo");
953 #[stable(feature = "command_access", since = "1.57.0")]
954 pub fn get_program(&self) -> &OsStr {
955 self.inner.get_program()
958 /// Returns an iterator of the arguments that will be passed to the program.
960 /// This does not include the path to the program as the first argument;
961 /// it only includes the arguments specified with [`Command::arg`] and
962 /// [`Command::args`].
967 /// use std::ffi::OsStr;
968 /// use std::process::Command;
970 /// let mut cmd = Command::new("echo");
971 /// cmd.arg("first").arg("second");
972 /// let args: Vec<&OsStr> = cmd.get_args().collect();
973 /// assert_eq!(args, &["first", "second"]);
975 #[stable(feature = "command_access", since = "1.57.0")]
976 pub fn get_args(&self) -> CommandArgs<'_> {
977 CommandArgs { inner: self.inner.get_args() }
980 /// Returns an iterator of the environment variables that will be set when
981 /// the process is spawned.
983 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
984 /// value is the key, and the second is the value, which is [`None`] if
985 /// the environment variable is to be explicitly removed.
987 /// This only includes environment variables explicitly set with
988 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
989 /// does not include environment variables that will be inherited by the
995 /// use std::ffi::OsStr;
996 /// use std::process::Command;
998 /// let mut cmd = Command::new("ls");
999 /// cmd.env("TERM", "dumb").env_remove("TZ");
1000 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1001 /// assert_eq!(envs, &[
1002 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1003 /// (OsStr::new("TZ"), None)
1006 #[stable(feature = "command_access", since = "1.57.0")]
1007 pub fn get_envs(&self) -> CommandEnvs<'_> {
1008 self.inner.get_envs()
1011 /// Returns the working directory for the child process.
1013 /// This returns [`None`] if the working directory will not be changed.
1018 /// use std::path::Path;
1019 /// use std::process::Command;
1021 /// let mut cmd = Command::new("ls");
1022 /// assert_eq!(cmd.get_current_dir(), None);
1023 /// cmd.current_dir("/bin");
1024 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1027 #[stable(feature = "command_access", since = "1.57.0")]
1028 pub fn get_current_dir(&self) -> Option<&Path> {
1029 self.inner.get_current_dir()
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl fmt::Debug for Command {
1035 /// Format the program and arguments of a Command for display. Any
1036 /// non-utf8 data is lossily converted using the utf8 replacement
1038 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043 impl AsInner<imp::Command> for Command {
1044 fn as_inner(&self) -> &imp::Command {
1049 impl AsInnerMut<imp::Command> for Command {
1050 fn as_inner_mut(&mut self) -> &mut imp::Command {
1055 /// An iterator over the command arguments.
1057 /// This struct is created by [`Command::get_args`]. See its documentation for
1059 #[must_use = "iterators are lazy and do nothing unless consumed"]
1060 #[stable(feature = "command_access", since = "1.57.0")]
1062 pub struct CommandArgs<'a> {
1063 inner: imp::CommandArgs<'a>,
1066 #[stable(feature = "command_access", since = "1.57.0")]
1067 impl<'a> Iterator for CommandArgs<'a> {
1068 type Item = &'a OsStr;
1069 fn next(&mut self) -> Option<&'a OsStr> {
1072 fn size_hint(&self) -> (usize, Option<usize>) {
1073 self.inner.size_hint()
1077 #[stable(feature = "command_access", since = "1.57.0")]
1078 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1079 fn len(&self) -> usize {
1082 fn is_empty(&self) -> bool {
1083 self.inner.is_empty()
1087 /// The output of a finished process.
1089 /// This is returned in a Result by either the [`output`] method of a
1090 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1093 /// [`output`]: Command::output
1094 /// [`wait_with_output`]: Child::wait_with_output
1095 #[derive(PartialEq, Eq, Clone)]
1096 #[stable(feature = "process", since = "1.0.0")]
1098 /// The status (exit code) of the process.
1099 #[stable(feature = "process", since = "1.0.0")]
1100 pub status: ExitStatus,
1101 /// The data that the process wrote to stdout.
1102 #[stable(feature = "process", since = "1.0.0")]
1103 pub stdout: Vec<u8>,
1104 /// The data that the process wrote to stderr.
1105 #[stable(feature = "process", since = "1.0.0")]
1106 pub stderr: Vec<u8>,
1109 // If either stderr or stdout are valid utf8 strings it prints the valid
1110 // strings, otherwise it prints the byte sequence instead
1111 #[stable(feature = "process_output_debug", since = "1.7.0")]
1112 impl fmt::Debug for Output {
1113 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1114 let stdout_utf8 = str::from_utf8(&self.stdout);
1115 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1117 Err(_) => &self.stdout,
1120 let stderr_utf8 = str::from_utf8(&self.stderr);
1121 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1123 Err(_) => &self.stderr,
1126 fmt.debug_struct("Output")
1127 .field("status", &self.status)
1128 .field("stdout", stdout_debug)
1129 .field("stderr", stderr_debug)
1134 /// Describes what to do with a standard I/O stream for a child process when
1135 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1137 /// [`stdin`]: Command::stdin
1138 /// [`stdout`]: Command::stdout
1139 /// [`stderr`]: Command::stderr
1140 #[stable(feature = "process", since = "1.0.0")]
1141 pub struct Stdio(imp::Stdio);
1144 /// A new pipe should be arranged to connect the parent and child processes.
1151 /// use std::process::{Command, Stdio};
1153 /// let output = Command::new("echo")
1154 /// .arg("Hello, world!")
1155 /// .stdout(Stdio::piped())
1157 /// .expect("Failed to execute command");
1159 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1160 /// // Nothing echoed to console
1166 /// use std::io::Write;
1167 /// use std::process::{Command, Stdio};
1169 /// let mut child = Command::new("rev")
1170 /// .stdin(Stdio::piped())
1171 /// .stdout(Stdio::piped())
1173 /// .expect("Failed to spawn child process");
1175 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1176 /// std::thread::spawn(move || {
1177 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1180 /// let output = child.wait_with_output().expect("Failed to read stdout");
1181 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1184 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1185 /// stdout and stderr at the same time may cause a deadlock.
1186 /// This is an issue when running any program that doesn't guarantee that it reads
1187 /// its entire stdin before writing more than a pipe buffer's worth of output.
1188 /// The size of a pipe buffer varies on different targets.
1191 #[stable(feature = "process", since = "1.0.0")]
1192 pub fn piped() -> Stdio {
1193 Stdio(imp::Stdio::MakePipe)
1196 /// The child inherits from the corresponding parent descriptor.
1203 /// use std::process::{Command, Stdio};
1205 /// let output = Command::new("echo")
1206 /// .arg("Hello, world!")
1207 /// .stdout(Stdio::inherit())
1209 /// .expect("Failed to execute command");
1211 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1212 /// // "Hello, world!" echoed to console
1218 /// use std::process::{Command, Stdio};
1219 /// use std::io::{self, Write};
1221 /// let output = Command::new("rev")
1222 /// .stdin(Stdio::inherit())
1223 /// .stdout(Stdio::piped())
1225 /// .expect("Failed to execute command");
1227 /// print!("You piped in the reverse of: ");
1228 /// io::stdout().write_all(&output.stdout).unwrap();
1231 #[stable(feature = "process", since = "1.0.0")]
1232 pub fn inherit() -> Stdio {
1233 Stdio(imp::Stdio::Inherit)
1236 /// This stream will be ignored. This is the equivalent of attaching the
1237 /// stream to `/dev/null`.
1244 /// use std::process::{Command, Stdio};
1246 /// let output = Command::new("echo")
1247 /// .arg("Hello, world!")
1248 /// .stdout(Stdio::null())
1250 /// .expect("Failed to execute command");
1252 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1253 /// // Nothing echoed to console
1259 /// use std::process::{Command, Stdio};
1261 /// let output = Command::new("rev")
1262 /// .stdin(Stdio::null())
1263 /// .stdout(Stdio::piped())
1265 /// .expect("Failed to execute command");
1267 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1268 /// // Ignores any piped-in input
1271 #[stable(feature = "process", since = "1.0.0")]
1272 pub fn null() -> Stdio {
1273 Stdio(imp::Stdio::Null)
1277 impl FromInner<imp::Stdio> for Stdio {
1278 fn from_inner(inner: imp::Stdio) -> Stdio {
1283 #[stable(feature = "std_debug", since = "1.16.0")]
1284 impl fmt::Debug for Stdio {
1285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1286 f.debug_struct("Stdio").finish_non_exhaustive()
1290 #[stable(feature = "stdio_from", since = "1.20.0")]
1291 impl From<ChildStdin> for Stdio {
1292 /// Converts a `ChildStdin` into a `Stdio`
1296 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1299 /// use std::process::{Command, Stdio};
1301 /// let reverse = Command::new("rev")
1302 /// .stdin(Stdio::piped())
1304 /// .expect("failed reverse command");
1306 /// let _echo = Command::new("echo")
1307 /// .arg("Hello, world!")
1308 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1310 /// .expect("failed echo command");
1312 /// // "!dlrow ,olleH" echoed to console
1314 fn from(child: ChildStdin) -> Stdio {
1315 Stdio::from_inner(child.into_inner().into())
1319 #[stable(feature = "stdio_from", since = "1.20.0")]
1320 impl From<ChildStdout> for Stdio {
1321 /// Converts a `ChildStdout` into a `Stdio`
1325 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1328 /// use std::process::{Command, Stdio};
1330 /// let hello = Command::new("echo")
1331 /// .arg("Hello, world!")
1332 /// .stdout(Stdio::piped())
1334 /// .expect("failed echo command");
1336 /// let reverse = Command::new("rev")
1337 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1339 /// .expect("failed reverse command");
1341 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1343 fn from(child: ChildStdout) -> Stdio {
1344 Stdio::from_inner(child.into_inner().into())
1348 #[stable(feature = "stdio_from", since = "1.20.0")]
1349 impl From<ChildStderr> for Stdio {
1350 /// Converts a `ChildStderr` into a `Stdio`
1355 /// use std::process::{Command, Stdio};
1357 /// let reverse = Command::new("rev")
1358 /// .arg("non_existing_file.txt")
1359 /// .stderr(Stdio::piped())
1361 /// .expect("failed reverse command");
1363 /// let cat = Command::new("cat")
1365 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1367 /// .expect("failed echo command");
1370 /// String::from_utf8_lossy(&cat.stdout),
1371 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1374 fn from(child: ChildStderr) -> Stdio {
1375 Stdio::from_inner(child.into_inner().into())
1379 #[stable(feature = "stdio_from", since = "1.20.0")]
1380 impl From<fs::File> for Stdio {
1381 /// Converts a `File` into a `Stdio`
1385 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1388 /// use std::fs::File;
1389 /// use std::process::Command;
1391 /// // With the `foo.txt` file containing `Hello, world!"
1392 /// let file = File::open("foo.txt").unwrap();
1394 /// let reverse = Command::new("rev")
1395 /// .stdin(file) // Implicit File conversion into a Stdio
1397 /// .expect("failed reverse command");
1399 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1401 fn from(file: fs::File) -> Stdio {
1402 Stdio::from_inner(file.into_inner().into())
1406 /// Describes the result of a process after it has terminated.
1408 /// This `struct` is used to represent the exit status or other termination of a child process.
1409 /// Child processes are created via the [`Command`] struct and their exit
1410 /// status is exposed through the [`status`] method, or the [`wait`] method
1411 /// of a [`Child`] process.
1413 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1414 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1416 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1417 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1419 /// [`status`]: Command::status
1420 /// [`wait`]: Child::wait
1422 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1423 // vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1424 // matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1425 // mean an underlying system call such as `_exit`.
1426 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1427 #[stable(feature = "process", since = "1.0.0")]
1428 pub struct ExitStatus(imp::ExitStatus);
1430 /// Allows extension traits within `std`.
1431 #[unstable(feature = "sealed", issue = "none")]
1432 impl crate::sealed::Sealed for ExitStatus {}
1435 /// Was termination successful? Returns a `Result`.
1440 /// #![feature(exit_status_error)]
1441 /// # if cfg!(unix) {
1442 /// use std::process::Command;
1444 /// let status = Command::new("ls")
1445 /// .arg("/dev/nonexistent")
1447 /// .expect("ls could not be executed");
1449 /// println!("ls: {}", status);
1450 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1451 /// # } // cfg!(unix)
1453 #[unstable(feature = "exit_status_error", issue = "84908")]
1454 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1455 self.0.exit_ok().map_err(ExitStatusError)
1458 /// Was termination successful? Signal termination is not considered a
1459 /// success, and success is defined as a zero exit status.
1464 /// use std::process::Command;
1466 /// let status = Command::new("mkdir")
1467 /// .arg("projects")
1469 /// .expect("failed to execute mkdir");
1471 /// if status.success() {
1472 /// println!("'projects/' directory created");
1474 /// println!("failed to create 'projects/' directory: {}", status);
1478 #[stable(feature = "process", since = "1.0.0")]
1479 pub fn success(&self) -> bool {
1480 self.0.exit_ok().is_ok()
1483 /// Returns the exit code of the process, if any.
1485 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1486 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1487 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1488 /// runtime system (often, for example, 255, 254, 127 or 126).
1490 /// On Unix, this will return `None` if the process was terminated by a signal.
1491 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1492 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1497 /// use std::process::Command;
1499 /// let status = Command::new("mkdir")
1500 /// .arg("projects")
1502 /// .expect("failed to execute mkdir");
1504 /// match status.code() {
1505 /// Some(code) => println!("Exited with status code: {}", code),
1506 /// None => println!("Process terminated by signal")
1510 #[stable(feature = "process", since = "1.0.0")]
1511 pub fn code(&self) -> Option<i32> {
1516 impl AsInner<imp::ExitStatus> for ExitStatus {
1517 fn as_inner(&self) -> &imp::ExitStatus {
1522 impl FromInner<imp::ExitStatus> for ExitStatus {
1523 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1528 #[stable(feature = "process", since = "1.0.0")]
1529 impl fmt::Display for ExitStatus {
1530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535 /// Allows extension traits within `std`.
1536 #[unstable(feature = "sealed", issue = "none")]
1537 impl crate::sealed::Sealed for ExitStatusError {}
1539 /// Describes the result of a process after it has failed
1541 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1546 /// #![feature(exit_status_error)]
1547 /// # if cfg!(unix) {
1548 /// use std::process::{Command, ExitStatusError};
1550 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1551 /// Command::new(cmd).status().unwrap().exit_ok()?;
1555 /// run("true").unwrap();
1556 /// run("false").unwrap_err();
1557 /// # } // cfg!(unix)
1559 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1560 #[unstable(feature = "exit_status_error", issue = "84908")]
1561 // The definition of imp::ExitStatusError should ideally be such that
1562 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1563 pub struct ExitStatusError(imp::ExitStatusError);
1565 #[unstable(feature = "exit_status_error", issue = "84908")]
1566 impl ExitStatusError {
1567 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1569 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1570 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1571 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1572 /// runtime system (often, for example, 255, 254, 127 or 126).
1574 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1575 /// handle such situations specially, consider using methods from
1576 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1578 /// If the process finished by calling `exit` with a nonzero value, this will return
1579 /// that exit status.
1581 /// If the error was something else, it will return `None`.
1583 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1584 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1589 /// #![feature(exit_status_error)]
1590 /// # #[cfg(unix)] {
1591 /// use std::process::Command;
1593 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1594 /// assert_eq!(bad.code(), Some(1));
1595 /// # } // #[cfg(unix)]
1598 pub fn code(&self) -> Option<i32> {
1599 self.code_nonzero().map(Into::into)
1602 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1604 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1606 /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1607 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1608 /// a type-level guarantee of nonzeroness.
1613 /// #![feature(exit_status_error)]
1614 /// # if cfg!(unix) {
1615 /// use std::convert::TryFrom;
1616 /// use std::num::NonZeroI32;
1617 /// use std::process::Command;
1619 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1620 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1621 /// # } // cfg!(unix)
1624 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1628 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1630 pub fn into_status(&self) -> ExitStatus {
1631 ExitStatus(self.0.into())
1635 #[unstable(feature = "exit_status_error", issue = "84908")]
1636 impl Into<ExitStatus> for ExitStatusError {
1637 fn into(self) -> ExitStatus {
1638 ExitStatus(self.0.into())
1642 #[unstable(feature = "exit_status_error", issue = "84908")]
1643 impl fmt::Display for ExitStatusError {
1644 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1645 write!(f, "process exited unsuccessfully: {}", self.into_status())
1649 #[unstable(feature = "exit_status_error", issue = "84908")]
1650 impl crate::error::Error for ExitStatusError {}
1652 /// This type represents the status code a process can return to its
1653 /// parent under normal termination.
1655 /// Numeric values used in this type don't have portable meanings, and
1656 /// different platforms may mask different amounts of them.
1658 /// For the platform's canonical successful and unsuccessful codes, see
1659 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1661 /// [`SUCCESS`]: ExitCode::SUCCESS
1662 /// [`FAILURE`]: ExitCode::FAILURE
1664 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1665 /// it was ultimately cut from that RFC, and thus this type is more subject
1666 /// to change even than the usual unstable item churn.
1668 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1669 #[derive(Clone, Copy, Debug)]
1670 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1671 pub struct ExitCode(imp::ExitCode);
1673 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1675 /// The canonical ExitCode for successful termination on this platform.
1677 /// Note that a `()`-returning `main` implicitly results in a successful
1678 /// termination, so there's no need to return this from `main` unless
1679 /// you're also returning other possible codes.
1680 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1681 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1683 /// The canonical ExitCode for unsuccessful termination on this platform.
1685 /// If you're only returning this and `SUCCESS` from `main`, consider
1686 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1687 /// return the same codes (but will also `eprintln!` the error).
1688 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1689 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1693 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1694 /// error is returned.
1696 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1698 /// This is equivalent to sending a SIGKILL on Unix platforms.
1705 /// use std::process::Command;
1707 /// let mut command = Command::new("yes");
1708 /// if let Ok(mut child) = command.spawn() {
1709 /// child.kill().expect("command wasn't running");
1711 /// println!("yes command didn't start");
1715 /// [`ErrorKind`]: io::ErrorKind
1716 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1717 #[stable(feature = "process", since = "1.0.0")]
1718 pub fn kill(&mut self) -> io::Result<()> {
1722 /// Returns the OS-assigned process identifier associated with this child.
1729 /// use std::process::Command;
1731 /// let mut command = Command::new("ls");
1732 /// if let Ok(child) = command.spawn() {
1733 /// println!("Child's ID is {}", child.id());
1735 /// println!("ls command didn't start");
1739 #[stable(feature = "process_id", since = "1.3.0")]
1740 pub fn id(&self) -> u32 {
1744 /// Waits for the child to exit completely, returning the status that it
1745 /// exited with. This function will continue to have the same return value
1746 /// after it has been called at least once.
1748 /// The stdin handle to the child process, if any, will be closed
1749 /// before waiting. This helps avoid deadlock: it ensures that the
1750 /// child does not block waiting for input from the parent, while
1751 /// the parent waits for the child to exit.
1758 /// use std::process::Command;
1760 /// let mut command = Command::new("ls");
1761 /// if let Ok(mut child) = command.spawn() {
1762 /// child.wait().expect("command wasn't running");
1763 /// println!("Child has finished its execution!");
1765 /// println!("ls command didn't start");
1768 #[stable(feature = "process", since = "1.0.0")]
1769 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1770 drop(self.stdin.take());
1771 self.handle.wait().map(ExitStatus)
1774 /// Attempts to collect the exit status of the child if it has already
1777 /// This function will not block the calling thread and will only
1778 /// check to see if the child process has exited or not. If the child has
1779 /// exited then on Unix the process ID is reaped. This function is
1780 /// guaranteed to repeatedly return a successful exit status so long as the
1781 /// child has already exited.
1783 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1784 /// exit status is not available at this time then `Ok(None)` is returned.
1785 /// If an error occurs, then that error is returned.
1787 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1794 /// use std::process::Command;
1796 /// let mut child = Command::new("ls").spawn().unwrap();
1798 /// match child.try_wait() {
1799 /// Ok(Some(status)) => println!("exited with: {}", status),
1801 /// println!("status not ready yet, let's really wait");
1802 /// let res = child.wait();
1803 /// println!("result: {:?}", res);
1805 /// Err(e) => println!("error attempting to wait: {}", e),
1808 #[stable(feature = "process_try_wait", since = "1.18.0")]
1809 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1810 Ok(self.handle.try_wait()?.map(ExitStatus))
1813 /// Simultaneously waits for the child to exit and collect all remaining
1814 /// output on the stdout/stderr handles, returning an `Output`
1817 /// The stdin handle to the child process, if any, will be closed
1818 /// before waiting. This helps avoid deadlock: it ensures that the
1819 /// child does not block waiting for input from the parent, while
1820 /// the parent waits for the child to exit.
1822 /// By default, stdin, stdout and stderr are inherited from the parent.
1823 /// In order to capture the output into this `Result<Output>` it is
1824 /// necessary to create new pipes between parent and child. Use
1825 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1830 /// use std::process::{Command, Stdio};
1832 /// let child = Command::new("/bin/cat")
1833 /// .arg("file.txt")
1834 /// .stdout(Stdio::piped())
1836 /// .expect("failed to execute child");
1838 /// let output = child
1839 /// .wait_with_output()
1840 /// .expect("failed to wait on child");
1842 /// assert!(output.status.success());
1845 #[stable(feature = "process", since = "1.0.0")]
1846 pub fn wait_with_output(mut self) -> io::Result<Output> {
1847 drop(self.stdin.take());
1849 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1850 match (self.stdout.take(), self.stderr.take()) {
1852 (Some(mut out), None) => {
1853 let res = out.read_to_end(&mut stdout);
1856 (None, Some(mut err)) => {
1857 let res = err.read_to_end(&mut stderr);
1860 (Some(out), Some(err)) => {
1861 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1866 let status = self.wait()?;
1867 Ok(Output { status, stdout, stderr })
1871 /// Terminates the current process with the specified exit code.
1873 /// This function will never return and will immediately terminate the current
1874 /// process. The exit code is passed through to the underlying OS and will be
1875 /// available for consumption by another process.
1877 /// Note that because this function never returns, and that it terminates the
1878 /// process, no destructors on the current stack or any other thread's stack
1879 /// will be run. If a clean shutdown is needed it is recommended to only call
1880 /// this function at a known point where there are no more destructors left
1883 /// ## Platform-specific behavior
1885 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1886 /// will be visible to a parent process inspecting the exit code. On most
1887 /// Unix-like platforms, only the eight least-significant bits are considered.
1891 /// Due to this function’s behavior regarding destructors, a conventional way
1892 /// to use the function is to extract the actual computation to another
1893 /// function and compute the exit code from its return value:
1896 /// fn run_app() -> Result<(), ()> {
1897 /// // Application logic here
1902 /// std::process::exit(match run_app() {
1905 /// eprintln!("error: {:?}", err);
1912 /// Due to [platform-specific behavior], the exit code for this example will be
1913 /// `0` on Linux, but `256` on Windows:
1916 /// use std::process;
1918 /// process::exit(0x0100);
1921 /// [platform-specific behavior]: #platform-specific-behavior
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 pub fn exit(code: i32) -> ! {
1924 crate::rt::cleanup();
1925 crate::sys::os::exit(code)
1928 /// Terminates the process in an abnormal fashion.
1930 /// The function will never return and will immediately terminate the current
1931 /// process in a platform specific "abnormal" manner.
1933 /// Note that because this function never returns, and that it terminates the
1934 /// process, no destructors on the current stack or any other thread's stack
1937 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
1938 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
1940 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1941 /// the current thread's stack and calls all destructors.
1942 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1943 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1944 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1946 /// If a clean shutdown is needed it is recommended to only call
1947 /// this function at a known point where there are no more destructors left
1950 /// The process's termination will be similar to that from the C `abort()`
1951 /// function. On Unix, the process will terminate with signal `SIGABRT`, which
1952 /// typically means that the shell prints "Aborted".
1957 /// use std::process;
1960 /// println!("aborting");
1962 /// process::abort();
1964 /// // execution never gets here
1968 /// The `abort` function terminates the process, so the destructor will not
1969 /// get run on the example below:
1972 /// use std::process;
1976 /// impl Drop for HasDrop {
1977 /// fn drop(&mut self) {
1978 /// println!("This will never be printed!");
1983 /// let _x = HasDrop;
1984 /// process::abort();
1985 /// // the destructor implemented for HasDrop will never get run
1989 /// [panic hook]: crate::panic::set_hook
1990 #[stable(feature = "process_abort", since = "1.17.0")]
1992 pub fn abort() -> ! {
1993 crate::sys::abort_internal();
1996 /// Returns the OS-assigned process identifier associated with this process.
2003 /// use std::process;
2005 /// println!("My pid is {}", process::id());
2010 #[stable(feature = "getpid", since = "1.26.0")]
2011 pub fn id() -> u32 {
2012 crate::sys::os::getpid()
2015 /// A trait for implementing arbitrary return types in the `main` function.
2017 /// The C-main function only supports to return integers as return type.
2018 /// So, every type implementing the `Termination` trait has to be converted
2021 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2022 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2023 #[cfg_attr(not(test), lang = "termination")]
2024 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2025 #[rustc_on_unimplemented(
2026 message = "`main` has invalid return type `{Self}`",
2027 label = "`main` can only return types that implement `{Termination}`"
2029 pub trait Termination {
2030 /// Is called to get the representation of the value as status code.
2031 /// This status code is returned to the operating system.
2032 fn report(self) -> i32;
2035 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2036 impl Termination for () {
2038 fn report(self) -> i32 {
2039 ExitCode::SUCCESS.report()
2043 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2044 impl<E: fmt::Debug> Termination for Result<(), E> {
2045 fn report(self) -> i32 {
2047 Ok(()) => ().report(),
2048 Err(err) => Err::<!, _>(err).report(),
2053 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2054 impl Termination for ! {
2055 fn report(self) -> i32 {
2060 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2061 impl<E: fmt::Debug> Termination for Result<!, E> {
2062 fn report(self) -> i32 {
2063 let Err(err) = self;
2064 eprintln!("Error: {:?}", err);
2065 ExitCode::FAILURE.report()
2069 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2070 impl<E: fmt::Debug> Termination for Result<Infallible, E> {
2071 fn report(self) -> i32 {
2072 let Err(err) = self;
2073 Err::<!, _>(err).report()
2077 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2078 impl Termination for ExitCode {
2080 fn report(self) -> i32 {