1 //! A module for working with processes.
3 //! This module is mostly concerned with spawning and interacting with child
4 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
7 //! # Spawning a process
9 //! The [`Command`] struct is used to configure and spawn processes:
12 //! use std::process::Command;
14 //! let output = Command::new("echo")
15 //! .arg("Hello world")
17 //! .expect("Failed to execute command");
19 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
22 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
23 //! to spawn a process. In particular, [`output`] spawns the child process and
24 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
25 //! that represents the spawned child process.
29 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
30 //! configured by passing an [`Stdio`] to the corresponding method on
31 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
32 //! example, piping output from one command into another command can be done
36 //! use std::process::{Command, Stdio};
38 //! // stdout must be configured with `Stdio::piped` in order to use
39 //! // `echo_child.stdout`
40 //! let echo_child = Command::new("echo")
41 //! .arg("Oh no, a tpyo!")
42 //! .stdout(Stdio::piped())
44 //! .expect("Failed to start echo process");
46 //! // Note that `echo_child` is moved here, but we won't be needing
47 //! // `echo_child` anymore
48 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
50 //! let mut sed_child = Command::new("sed")
51 //! .arg("s/tpyo/typo/")
52 //! .stdin(Stdio::from(echo_out))
53 //! .stdout(Stdio::piped())
55 //! .expect("Failed to start sed process");
57 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
58 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
61 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
62 //! [`ChildStdin`] implements [`Write`]:
65 //! use std::process::{Command, Stdio};
66 //! use std::io::Write;
68 //! let mut child = Command::new("/bin/cat")
69 //! .stdin(Stdio::piped())
70 //! .stdout(Stdio::piped())
72 //! .expect("failed to execute child");
74 //! // If the child process fills its stdout buffer, it may end up
75 //! // waiting until the parent reads the stdout, and not be able to
76 //! // read stdin in the meantime, causing a deadlock.
77 //! // Writing from another thread ensures that stdout is being read
78 //! // at the same time, avoiding the problem.
79 //! let mut stdin = child.stdin.take().expect("failed to get stdin");
80 //! std::thread::spawn(move || {
81 //! stdin.write_all(b"test").expect("failed to write to stdin");
84 //! let output = child
85 //! .wait_with_output()
86 //! .expect("failed to wait on child");
88 //! assert_eq!(b"test", output.stdout.as_slice());
91 //! [`spawn`]: Command::spawn
92 //! [`output`]: Command::output
94 //! [`stdout`]: Command::stdout
95 //! [`stdin`]: Command::stdin
96 //! [`stderr`]: Command::stderr
98 //! [`Write`]: io::Write
99 //! [`Read`]: io::Read
101 #![stable(feature = "process", since = "1.0.0")]
102 #![deny(unsafe_op_in_unsafe_fn)]
104 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
107 use crate::io::prelude::*;
109 use crate::ffi::OsStr;
112 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
113 use crate::num::NonZeroI32;
114 use crate::path::Path;
116 use crate::sys::pipe::{read2, AnonPipe};
117 use crate::sys::process as imp;
118 #[stable(feature = "command_access", since = "1.57.0")]
119 pub use crate::sys_common::process::CommandEnvs;
120 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
122 /// Representation of a running or exited child process.
124 /// This structure is used to represent and manage child processes. A child
125 /// process is created via the [`Command`] struct, which configures the
126 /// spawning process and can itself be constructed using a builder-style
129 /// There is no implementation of [`Drop`] for child processes,
130 /// so if you do not ensure the `Child` has exited then it will continue to
131 /// run, even after the `Child` handle to the child process has gone out of
134 /// Calling [`wait`] (or other functions that wrap around it) will make
135 /// the parent process wait until the child has actually exited before
140 /// On some systems, calling [`wait`] or similar is necessary for the OS to
141 /// release resources. A process that terminated but has not been waited on is
142 /// still around as a "zombie". Leaving too many zombies around may exhaust
143 /// global resources (for example process IDs).
145 /// The standard library does *not* automatically wait on child processes (not
146 /// even if the `Child` is dropped), it is up to the application developer to do
147 /// so. As a consequence, dropping `Child` handles without waiting on them first
148 /// is not recommended in long-running applications.
153 /// use std::process::Command;
155 /// let mut child = Command::new("/bin/cat")
158 /// .expect("failed to execute child");
160 /// let ecode = child.wait()
161 /// .expect("failed to wait on child");
163 /// assert!(ecode.success());
166 /// [`wait`]: Child::wait
167 #[stable(feature = "process", since = "1.0.0")]
169 pub(crate) handle: imp::Process,
171 /// The handle for writing to the child's standard input (stdin), if it has
172 /// been captured. To avoid partially moving
173 /// the `child` and thus blocking yourself from calling
174 /// functions on `child` while using `stdin`,
175 /// you might find it helpful:
177 /// ```compile_fail,E0425
178 /// let stdin = child.stdin.take().unwrap();
180 #[stable(feature = "process", since = "1.0.0")]
181 pub stdin: Option<ChildStdin>,
183 /// The handle for reading from the child's standard output (stdout), if it
184 /// has been captured. You might find it helpful to do
186 /// ```compile_fail,E0425
187 /// let stdout = child.stdout.take().unwrap();
190 /// to avoid partially moving the `child` and thus blocking yourself from calling
191 /// functions on `child` while using `stdout`.
192 #[stable(feature = "process", since = "1.0.0")]
193 pub stdout: Option<ChildStdout>,
195 /// The handle for reading from the child's standard error (stderr), if it
196 /// has been captured. You might find it helpful to do
198 /// ```compile_fail,E0425
199 /// let stderr = child.stderr.take().unwrap();
202 /// to avoid partially moving the `child` and thus blocking yourself from calling
203 /// functions on `child` while using `stderr`.
204 #[stable(feature = "process", since = "1.0.0")]
205 pub stderr: Option<ChildStderr>,
208 /// Allows extension traits within `std`.
209 #[unstable(feature = "sealed", issue = "none")]
210 impl crate::sealed::Sealed for Child {}
212 impl AsInner<imp::Process> for Child {
213 fn as_inner(&self) -> &imp::Process {
218 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
219 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
222 stdin: io.stdin.map(ChildStdin::from_inner),
223 stdout: io.stdout.map(ChildStdout::from_inner),
224 stderr: io.stderr.map(ChildStderr::from_inner),
229 impl IntoInner<imp::Process> for Child {
230 fn into_inner(self) -> imp::Process {
235 #[stable(feature = "std_debug", since = "1.16.0")]
236 impl fmt::Debug for Child {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.debug_struct("Child")
239 .field("stdin", &self.stdin)
240 .field("stdout", &self.stdout)
241 .field("stderr", &self.stderr)
242 .finish_non_exhaustive()
246 /// A handle to a child process's standard input (stdin).
248 /// This struct is used in the [`stdin`] field on [`Child`].
250 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
251 /// file handle will be closed. If the child process was blocked on input prior
252 /// to being dropped, it will become unblocked after dropping.
254 /// [`stdin`]: Child::stdin
256 #[stable(feature = "process", since = "1.0.0")]
257 pub struct ChildStdin {
261 // In addition to the `impl`s here, `ChildStdin` also has `impl`s for
262 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
263 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
264 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
265 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
267 #[stable(feature = "process", since = "1.0.0")]
268 impl Write for ChildStdin {
269 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
273 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
274 (&*self).write_vectored(bufs)
277 fn is_write_vectored(&self) -> bool {
278 io::Write::is_write_vectored(&&*self)
281 fn flush(&mut self) -> io::Result<()> {
286 #[stable(feature = "write_mt", since = "1.48.0")]
287 impl Write for &ChildStdin {
288 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
289 self.inner.write(buf)
292 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
293 self.inner.write_vectored(bufs)
296 fn is_write_vectored(&self) -> bool {
297 self.inner.is_write_vectored()
300 fn flush(&mut self) -> io::Result<()> {
305 impl AsInner<AnonPipe> for ChildStdin {
306 fn as_inner(&self) -> &AnonPipe {
311 impl IntoInner<AnonPipe> for ChildStdin {
312 fn into_inner(self) -> AnonPipe {
317 impl FromInner<AnonPipe> for ChildStdin {
318 fn from_inner(pipe: AnonPipe) -> ChildStdin {
319 ChildStdin { inner: pipe }
323 #[stable(feature = "std_debug", since = "1.16.0")]
324 impl fmt::Debug for ChildStdin {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.debug_struct("ChildStdin").finish_non_exhaustive()
330 /// A handle to a child process's standard output (stdout).
332 /// This struct is used in the [`stdout`] field on [`Child`].
334 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
335 /// underlying file handle will be closed.
337 /// [`stdout`]: Child::stdout
339 #[stable(feature = "process", since = "1.0.0")]
340 pub struct ChildStdout {
344 // In addition to the `impl`s here, `ChildStdout` also has `impl`s for
345 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
346 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
347 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
348 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
350 #[stable(feature = "process", since = "1.0.0")]
351 impl Read for ChildStdout {
352 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
356 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
357 self.inner.read_vectored(bufs)
361 fn is_read_vectored(&self) -> bool {
362 self.inner.is_read_vectored()
366 unsafe fn initializer(&self) -> Initializer {
367 // SAFETY: Read is guaranteed to work on uninitialized memory
368 unsafe { Initializer::nop() }
372 impl AsInner<AnonPipe> for ChildStdout {
373 fn as_inner(&self) -> &AnonPipe {
378 impl IntoInner<AnonPipe> for ChildStdout {
379 fn into_inner(self) -> AnonPipe {
384 impl FromInner<AnonPipe> for ChildStdout {
385 fn from_inner(pipe: AnonPipe) -> ChildStdout {
386 ChildStdout { inner: pipe }
390 #[stable(feature = "std_debug", since = "1.16.0")]
391 impl fmt::Debug for ChildStdout {
392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393 f.debug_struct("ChildStdout").finish_non_exhaustive()
397 /// A handle to a child process's stderr.
399 /// This struct is used in the [`stderr`] field on [`Child`].
401 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
402 /// underlying file handle will be closed.
404 /// [`stderr`]: Child::stderr
406 #[stable(feature = "process", since = "1.0.0")]
407 pub struct ChildStderr {
411 // In addition to the `impl`s here, `ChildStderr` also has `impl`s for
412 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
413 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
414 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
415 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
417 #[stable(feature = "process", since = "1.0.0")]
418 impl Read for ChildStderr {
419 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
423 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
424 self.inner.read_vectored(bufs)
428 fn is_read_vectored(&self) -> bool {
429 self.inner.is_read_vectored()
433 unsafe fn initializer(&self) -> Initializer {
434 // SAFETY: Read is guaranteed to work on uninitialized memory
435 unsafe { Initializer::nop() }
439 impl AsInner<AnonPipe> for ChildStderr {
440 fn as_inner(&self) -> &AnonPipe {
445 impl IntoInner<AnonPipe> for ChildStderr {
446 fn into_inner(self) -> AnonPipe {
451 impl FromInner<AnonPipe> for ChildStderr {
452 fn from_inner(pipe: AnonPipe) -> ChildStderr {
453 ChildStderr { inner: pipe }
457 #[stable(feature = "std_debug", since = "1.16.0")]
458 impl fmt::Debug for ChildStderr {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 f.debug_struct("ChildStderr").finish_non_exhaustive()
464 /// A process builder, providing fine-grained control
465 /// over how a new process should be spawned.
467 /// A default configuration can be
468 /// generated using `Command::new(program)`, where `program` gives a path to the
469 /// program to be executed. Additional builder methods allow the configuration
470 /// to be changed (for example, by adding arguments) prior to spawning:
473 /// use std::process::Command;
475 /// let output = if cfg!(target_os = "windows") {
476 /// Command::new("cmd")
477 /// .args(["/C", "echo hello"])
479 /// .expect("failed to execute process")
481 /// Command::new("sh")
483 /// .arg("echo hello")
485 /// .expect("failed to execute process")
488 /// let hello = output.stdout;
491 /// `Command` can be reused to spawn multiple processes. The builder methods
492 /// change the command without needing to immediately spawn the process.
495 /// use std::process::Command;
497 /// let mut echo_hello = Command::new("sh");
498 /// echo_hello.arg("-c")
499 /// .arg("echo hello");
500 /// let hello_1 = echo_hello.output().expect("failed to execute process");
501 /// let hello_2 = echo_hello.output().expect("failed to execute process");
504 /// Similarly, you can call builder methods after spawning a process and then
505 /// spawn a new process with the modified settings.
508 /// use std::process::Command;
510 /// let mut list_dir = Command::new("ls");
512 /// // Execute `ls` in the current directory of the program.
513 /// list_dir.status().expect("process failed to execute");
517 /// // Change `ls` to execute in the root directory.
518 /// list_dir.current_dir("/");
520 /// // And then execute `ls` again but in the root directory.
521 /// list_dir.status().expect("process failed to execute");
523 #[stable(feature = "process", since = "1.0.0")]
528 /// Allows extension traits within `std`.
529 #[unstable(feature = "sealed", issue = "none")]
530 impl crate::sealed::Sealed for Command {}
533 /// Constructs a new `Command` for launching the program at
534 /// path `program`, with the following default configuration:
536 /// * No arguments to the program
537 /// * Inherit the current process's environment
538 /// * Inherit the current process's working directory
539 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
541 /// Builder methods are provided to change these defaults and
542 /// otherwise configure the process.
544 /// If `program` is not an absolute path, the `PATH` will be searched in
545 /// an OS-defined way.
547 /// The search path to be used may be controlled by setting the
548 /// `PATH` environment variable on the Command,
549 /// but this has some implementation limitations on Windows
550 /// (see issue #37519).
557 /// use std::process::Command;
559 /// Command::new("sh")
561 /// .expect("sh command failed to start");
563 #[stable(feature = "process", since = "1.0.0")]
564 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
565 Command { inner: imp::Command::new(program.as_ref()) }
568 /// Adds an argument to pass to the program.
570 /// Only one argument can be passed per use. So instead of:
573 /// # std::process::Command::new("sh")
574 /// .arg("-C /path/to/repo")
581 /// # std::process::Command::new("sh")
583 /// .arg("/path/to/repo")
587 /// To pass multiple arguments see [`args`].
589 /// [`args`]: Command::args
591 /// Note that the argument is not passed through a shell, but given
592 /// literally to the program. This means that shell syntax like quotes,
593 /// escaped characters, word splitting, glob patterns, substitution, etc.
601 /// use std::process::Command;
603 /// Command::new("ls")
607 /// .expect("ls command failed to start");
609 #[stable(feature = "process", since = "1.0.0")]
610 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
611 self.inner.arg(arg.as_ref());
615 /// Adds multiple arguments to pass to the program.
617 /// To pass a single argument see [`arg`].
619 /// [`arg`]: Command::arg
621 /// Note that the arguments are not passed through a shell, but given
622 /// literally to the program. This means that shell syntax like quotes,
623 /// escaped characters, word splitting, glob patterns, substitution, etc.
631 /// use std::process::Command;
633 /// Command::new("ls")
634 /// .args(["-l", "-a"])
636 /// .expect("ls command failed to start");
638 #[stable(feature = "process", since = "1.0.0")]
639 pub fn args<I, S>(&mut self, args: I) -> &mut Command
641 I: IntoIterator<Item = S>,
645 self.arg(arg.as_ref());
650 /// Inserts or updates an environment variable mapping.
652 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
653 /// and case-sensitive on all other platforms.
660 /// use std::process::Command;
662 /// Command::new("ls")
663 /// .env("PATH", "/bin")
665 /// .expect("ls command failed to start");
667 #[stable(feature = "process", since = "1.0.0")]
668 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
673 self.inner.env_mut().set(key.as_ref(), val.as_ref());
677 /// Adds or updates multiple environment variable mappings.
684 /// use std::process::{Command, Stdio};
686 /// use std::collections::HashMap;
688 /// let filtered_env : HashMap<String, String> =
689 /// env::vars().filter(|&(ref k, _)|
690 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
693 /// Command::new("printenv")
694 /// .stdin(Stdio::null())
695 /// .stdout(Stdio::inherit())
697 /// .envs(&filtered_env)
699 /// .expect("printenv failed to start");
701 #[stable(feature = "command_envs", since = "1.19.0")]
702 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
704 I: IntoIterator<Item = (K, V)>,
708 for (ref key, ref val) in vars {
709 self.inner.env_mut().set(key.as_ref(), val.as_ref());
714 /// Removes an environment variable mapping.
721 /// use std::process::Command;
723 /// Command::new("ls")
724 /// .env_remove("PATH")
726 /// .expect("ls command failed to start");
728 #[stable(feature = "process", since = "1.0.0")]
729 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
730 self.inner.env_mut().remove(key.as_ref());
734 /// Clears the entire environment map for the child process.
741 /// use std::process::Command;
743 /// Command::new("ls")
746 /// .expect("ls command failed to start");
748 #[stable(feature = "process", since = "1.0.0")]
749 pub fn env_clear(&mut self) -> &mut Command {
750 self.inner.env_mut().clear();
754 /// Sets the working directory for the child process.
756 /// # Platform-specific behavior
758 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
759 /// whether it should be interpreted relative to the parent's working
760 /// directory or relative to `current_dir`. The behavior in this case is
761 /// platform specific and unstable, and it's recommended to use
762 /// [`canonicalize`] to get an absolute program path instead.
769 /// use std::process::Command;
771 /// Command::new("ls")
772 /// .current_dir("/bin")
774 /// .expect("ls command failed to start");
777 /// [`canonicalize`]: crate::fs::canonicalize
778 #[stable(feature = "process", since = "1.0.0")]
779 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
780 self.inner.cwd(dir.as_ref().as_ref());
784 /// Configuration for the child process's standard input (stdin) handle.
786 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
787 /// defaults to [`piped`] when used with `output`.
789 /// [`inherit`]: Stdio::inherit
790 /// [`piped`]: Stdio::piped
797 /// use std::process::{Command, Stdio};
799 /// Command::new("ls")
800 /// .stdin(Stdio::null())
802 /// .expect("ls command failed to start");
804 #[stable(feature = "process", since = "1.0.0")]
805 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
806 self.inner.stdin(cfg.into().0);
810 /// Configuration for the child process's standard output (stdout) handle.
812 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
813 /// defaults to [`piped`] when used with `output`.
815 /// [`inherit`]: Stdio::inherit
816 /// [`piped`]: Stdio::piped
823 /// use std::process::{Command, Stdio};
825 /// Command::new("ls")
826 /// .stdout(Stdio::null())
828 /// .expect("ls command failed to start");
830 #[stable(feature = "process", since = "1.0.0")]
831 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
832 self.inner.stdout(cfg.into().0);
836 /// Configuration for the child process's standard error (stderr) handle.
838 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
839 /// defaults to [`piped`] when used with `output`.
841 /// [`inherit`]: Stdio::inherit
842 /// [`piped`]: Stdio::piped
849 /// use std::process::{Command, Stdio};
851 /// Command::new("ls")
852 /// .stderr(Stdio::null())
854 /// .expect("ls command failed to start");
856 #[stable(feature = "process", since = "1.0.0")]
857 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
858 self.inner.stderr(cfg.into().0);
862 /// Executes the command as a child process, returning a handle to it.
864 /// By default, stdin, stdout and stderr are inherited from the parent.
871 /// use std::process::Command;
873 /// Command::new("ls")
875 /// .expect("ls command failed to start");
877 #[stable(feature = "process", since = "1.0.0")]
878 pub fn spawn(&mut self) -> io::Result<Child> {
879 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
882 /// Executes the command as a child process, waiting for it to finish and
883 /// collecting all of its output.
885 /// By default, stdout and stderr are captured (and used to provide the
886 /// resulting output). Stdin is not inherited from the parent and any
887 /// attempt by the child process to read from the stdin stream will result
888 /// in the stream immediately closing.
893 /// use std::process::Command;
894 /// use std::io::{self, Write};
895 /// let output = Command::new("/bin/cat")
898 /// .expect("failed to execute process");
900 /// println!("status: {}", output.status);
901 /// io::stdout().write_all(&output.stdout).unwrap();
902 /// io::stderr().write_all(&output.stderr).unwrap();
904 /// assert!(output.status.success());
906 #[stable(feature = "process", since = "1.0.0")]
907 pub fn output(&mut self) -> io::Result<Output> {
909 .spawn(imp::Stdio::MakePipe, false)
910 .map(Child::from_inner)
911 .and_then(|p| p.wait_with_output())
914 /// Executes a command as a child process, waiting for it to finish and
915 /// collecting its status.
917 /// By default, stdin, stdout and stderr are inherited from the parent.
922 /// use std::process::Command;
924 /// let status = Command::new("/bin/cat")
927 /// .expect("failed to execute process");
929 /// println!("process finished with: {}", status);
931 /// assert!(status.success());
933 #[stable(feature = "process", since = "1.0.0")]
934 pub fn status(&mut self) -> io::Result<ExitStatus> {
936 .spawn(imp::Stdio::Inherit, true)
937 .map(Child::from_inner)
938 .and_then(|mut p| p.wait())
941 /// Returns the path to the program that was given to [`Command::new`].
946 /// use std::process::Command;
948 /// let cmd = Command::new("echo");
949 /// assert_eq!(cmd.get_program(), "echo");
952 #[stable(feature = "command_access", since = "1.57.0")]
953 pub fn get_program(&self) -> &OsStr {
954 self.inner.get_program()
957 /// Returns an iterator of the arguments that will be passed to the program.
959 /// This does not include the path to the program as the first argument;
960 /// it only includes the arguments specified with [`Command::arg`] and
961 /// [`Command::args`].
966 /// use std::ffi::OsStr;
967 /// use std::process::Command;
969 /// let mut cmd = Command::new("echo");
970 /// cmd.arg("first").arg("second");
971 /// let args: Vec<&OsStr> = cmd.get_args().collect();
972 /// assert_eq!(args, &["first", "second"]);
974 #[stable(feature = "command_access", since = "1.57.0")]
975 pub fn get_args(&self) -> CommandArgs<'_> {
976 CommandArgs { inner: self.inner.get_args() }
979 /// Returns an iterator of the environment variables that will be set when
980 /// the process is spawned.
982 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
983 /// value is the key, and the second is the value, which is [`None`] if
984 /// the environment variable is to be explicitly removed.
986 /// This only includes environment variables explicitly set with
987 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
988 /// does not include environment variables that will be inherited by the
994 /// use std::ffi::OsStr;
995 /// use std::process::Command;
997 /// let mut cmd = Command::new("ls");
998 /// cmd.env("TERM", "dumb").env_remove("TZ");
999 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1000 /// assert_eq!(envs, &[
1001 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1002 /// (OsStr::new("TZ"), None)
1005 #[stable(feature = "command_access", since = "1.57.0")]
1006 pub fn get_envs(&self) -> CommandEnvs<'_> {
1007 self.inner.get_envs()
1010 /// Returns the working directory for the child process.
1012 /// This returns [`None`] if the working directory will not be changed.
1017 /// use std::path::Path;
1018 /// use std::process::Command;
1020 /// let mut cmd = Command::new("ls");
1021 /// assert_eq!(cmd.get_current_dir(), None);
1022 /// cmd.current_dir("/bin");
1023 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1026 #[stable(feature = "command_access", since = "1.57.0")]
1027 pub fn get_current_dir(&self) -> Option<&Path> {
1028 self.inner.get_current_dir()
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 impl fmt::Debug for Command {
1034 /// Format the program and arguments of a Command for display. Any
1035 /// non-utf8 data is lossily converted using the utf8 replacement
1037 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1042 impl AsInner<imp::Command> for Command {
1043 fn as_inner(&self) -> &imp::Command {
1048 impl AsInnerMut<imp::Command> for Command {
1049 fn as_inner_mut(&mut self) -> &mut imp::Command {
1054 /// An iterator over the command arguments.
1056 /// This struct is created by [`Command::get_args`]. See its documentation for
1058 #[must_use = "iterators are lazy and do nothing unless consumed"]
1059 #[stable(feature = "command_access", since = "1.57.0")]
1061 pub struct CommandArgs<'a> {
1062 inner: imp::CommandArgs<'a>,
1065 #[stable(feature = "command_access", since = "1.57.0")]
1066 impl<'a> Iterator for CommandArgs<'a> {
1067 type Item = &'a OsStr;
1068 fn next(&mut self) -> Option<&'a OsStr> {
1071 fn size_hint(&self) -> (usize, Option<usize>) {
1072 self.inner.size_hint()
1076 #[stable(feature = "command_access", since = "1.57.0")]
1077 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1078 fn len(&self) -> usize {
1081 fn is_empty(&self) -> bool {
1082 self.inner.is_empty()
1086 /// The output of a finished process.
1088 /// This is returned in a Result by either the [`output`] method of a
1089 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1092 /// [`output`]: Command::output
1093 /// [`wait_with_output`]: Child::wait_with_output
1094 #[derive(PartialEq, Eq, Clone)]
1095 #[stable(feature = "process", since = "1.0.0")]
1097 /// The status (exit code) of the process.
1098 #[stable(feature = "process", since = "1.0.0")]
1099 pub status: ExitStatus,
1100 /// The data that the process wrote to stdout.
1101 #[stable(feature = "process", since = "1.0.0")]
1102 pub stdout: Vec<u8>,
1103 /// The data that the process wrote to stderr.
1104 #[stable(feature = "process", since = "1.0.0")]
1105 pub stderr: Vec<u8>,
1108 // If either stderr or stdout are valid utf8 strings it prints the valid
1109 // strings, otherwise it prints the byte sequence instead
1110 #[stable(feature = "process_output_debug", since = "1.7.0")]
1111 impl fmt::Debug for Output {
1112 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1113 let stdout_utf8 = str::from_utf8(&self.stdout);
1114 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1116 Err(_) => &self.stdout,
1119 let stderr_utf8 = str::from_utf8(&self.stderr);
1120 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1122 Err(_) => &self.stderr,
1125 fmt.debug_struct("Output")
1126 .field("status", &self.status)
1127 .field("stdout", stdout_debug)
1128 .field("stderr", stderr_debug)
1133 /// Describes what to do with a standard I/O stream for a child process when
1134 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1136 /// [`stdin`]: Command::stdin
1137 /// [`stdout`]: Command::stdout
1138 /// [`stderr`]: Command::stderr
1139 #[stable(feature = "process", since = "1.0.0")]
1140 pub struct Stdio(imp::Stdio);
1143 /// A new pipe should be arranged to connect the parent and child processes.
1150 /// use std::process::{Command, Stdio};
1152 /// let output = Command::new("echo")
1153 /// .arg("Hello, world!")
1154 /// .stdout(Stdio::piped())
1156 /// .expect("Failed to execute command");
1158 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1159 /// // Nothing echoed to console
1165 /// use std::io::Write;
1166 /// use std::process::{Command, Stdio};
1168 /// let mut child = Command::new("rev")
1169 /// .stdin(Stdio::piped())
1170 /// .stdout(Stdio::piped())
1172 /// .expect("Failed to spawn child process");
1174 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1175 /// std::thread::spawn(move || {
1176 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1179 /// let output = child.wait_with_output().expect("Failed to read stdout");
1180 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1183 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1184 /// stdout and stderr at the same time may cause a deadlock.
1185 /// This is an issue when running any program that doesn't guarantee that it reads
1186 /// its entire stdin before writing more than a pipe buffer's worth of output.
1187 /// The size of a pipe buffer varies on different targets.
1190 #[stable(feature = "process", since = "1.0.0")]
1191 pub fn piped() -> Stdio {
1192 Stdio(imp::Stdio::MakePipe)
1195 /// The child inherits from the corresponding parent descriptor.
1202 /// use std::process::{Command, Stdio};
1204 /// let output = Command::new("echo")
1205 /// .arg("Hello, world!")
1206 /// .stdout(Stdio::inherit())
1208 /// .expect("Failed to execute command");
1210 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1211 /// // "Hello, world!" echoed to console
1217 /// use std::process::{Command, Stdio};
1218 /// use std::io::{self, Write};
1220 /// let output = Command::new("rev")
1221 /// .stdin(Stdio::inherit())
1222 /// .stdout(Stdio::piped())
1224 /// .expect("Failed to execute command");
1226 /// print!("You piped in the reverse of: ");
1227 /// io::stdout().write_all(&output.stdout).unwrap();
1230 #[stable(feature = "process", since = "1.0.0")]
1231 pub fn inherit() -> Stdio {
1232 Stdio(imp::Stdio::Inherit)
1235 /// This stream will be ignored. This is the equivalent of attaching the
1236 /// stream to `/dev/null`.
1243 /// use std::process::{Command, Stdio};
1245 /// let output = Command::new("echo")
1246 /// .arg("Hello, world!")
1247 /// .stdout(Stdio::null())
1249 /// .expect("Failed to execute command");
1251 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1252 /// // Nothing echoed to console
1258 /// use std::process::{Command, Stdio};
1260 /// let output = Command::new("rev")
1261 /// .stdin(Stdio::null())
1262 /// .stdout(Stdio::piped())
1264 /// .expect("Failed to execute command");
1266 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1267 /// // Ignores any piped-in input
1270 #[stable(feature = "process", since = "1.0.0")]
1271 pub fn null() -> Stdio {
1272 Stdio(imp::Stdio::Null)
1276 impl FromInner<imp::Stdio> for Stdio {
1277 fn from_inner(inner: imp::Stdio) -> Stdio {
1282 #[stable(feature = "std_debug", since = "1.16.0")]
1283 impl fmt::Debug for Stdio {
1284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1285 f.debug_struct("Stdio").finish_non_exhaustive()
1289 #[stable(feature = "stdio_from", since = "1.20.0")]
1290 impl From<ChildStdin> for Stdio {
1291 /// Converts a `ChildStdin` into a `Stdio`
1295 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1298 /// use std::process::{Command, Stdio};
1300 /// let reverse = Command::new("rev")
1301 /// .stdin(Stdio::piped())
1303 /// .expect("failed reverse command");
1305 /// let _echo = Command::new("echo")
1306 /// .arg("Hello, world!")
1307 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1309 /// .expect("failed echo command");
1311 /// // "!dlrow ,olleH" echoed to console
1313 fn from(child: ChildStdin) -> Stdio {
1314 Stdio::from_inner(child.into_inner().into())
1318 #[stable(feature = "stdio_from", since = "1.20.0")]
1319 impl From<ChildStdout> for Stdio {
1320 /// Converts a `ChildStdout` into a `Stdio`
1324 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1327 /// use std::process::{Command, Stdio};
1329 /// let hello = Command::new("echo")
1330 /// .arg("Hello, world!")
1331 /// .stdout(Stdio::piped())
1333 /// .expect("failed echo command");
1335 /// let reverse = Command::new("rev")
1336 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1338 /// .expect("failed reverse command");
1340 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1342 fn from(child: ChildStdout) -> Stdio {
1343 Stdio::from_inner(child.into_inner().into())
1347 #[stable(feature = "stdio_from", since = "1.20.0")]
1348 impl From<ChildStderr> for Stdio {
1349 /// Converts a `ChildStderr` into a `Stdio`
1354 /// use std::process::{Command, Stdio};
1356 /// let reverse = Command::new("rev")
1357 /// .arg("non_existing_file.txt")
1358 /// .stderr(Stdio::piped())
1360 /// .expect("failed reverse command");
1362 /// let cat = Command::new("cat")
1364 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1366 /// .expect("failed echo command");
1369 /// String::from_utf8_lossy(&cat.stdout),
1370 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1373 fn from(child: ChildStderr) -> Stdio {
1374 Stdio::from_inner(child.into_inner().into())
1378 #[stable(feature = "stdio_from", since = "1.20.0")]
1379 impl From<fs::File> for Stdio {
1380 /// Converts a `File` into a `Stdio`
1384 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1387 /// use std::fs::File;
1388 /// use std::process::Command;
1390 /// // With the `foo.txt` file containing `Hello, world!"
1391 /// let file = File::open("foo.txt").unwrap();
1393 /// let reverse = Command::new("rev")
1394 /// .stdin(file) // Implicit File conversion into a Stdio
1396 /// .expect("failed reverse command");
1398 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1400 fn from(file: fs::File) -> Stdio {
1401 Stdio::from_inner(file.into_inner().into())
1405 /// Describes the result of a process after it has terminated.
1407 /// This `struct` is used to represent the exit status or other termination of a child process.
1408 /// Child processes are created via the [`Command`] struct and their exit
1409 /// status is exposed through the [`status`] method, or the [`wait`] method
1410 /// of a [`Child`] process.
1412 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1413 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1415 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1416 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1418 /// [`status`]: Command::status
1419 /// [`wait`]: Child::wait
1421 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1422 // vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1423 // matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1424 // mean an underlying system call such as `_exit`.
1425 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1426 #[stable(feature = "process", since = "1.0.0")]
1427 pub struct ExitStatus(imp::ExitStatus);
1429 /// Allows extension traits within `std`.
1430 #[unstable(feature = "sealed", issue = "none")]
1431 impl crate::sealed::Sealed for ExitStatus {}
1434 /// Was termination successful? Returns a `Result`.
1439 /// #![feature(exit_status_error)]
1440 /// # if cfg!(unix) {
1441 /// use std::process::Command;
1443 /// let status = Command::new("ls")
1444 /// .arg("/dev/nonexistent")
1446 /// .expect("ls could not be executed");
1448 /// println!("ls: {}", status);
1449 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1450 /// # } // cfg!(unix)
1452 #[unstable(feature = "exit_status_error", issue = "84908")]
1453 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1454 self.0.exit_ok().map_err(ExitStatusError)
1457 /// Was termination successful? Signal termination is not considered a
1458 /// success, and success is defined as a zero exit status.
1463 /// use std::process::Command;
1465 /// let status = Command::new("mkdir")
1466 /// .arg("projects")
1468 /// .expect("failed to execute mkdir");
1470 /// if status.success() {
1471 /// println!("'projects/' directory created");
1473 /// println!("failed to create 'projects/' directory: {}", status);
1477 #[stable(feature = "process", since = "1.0.0")]
1478 pub fn success(&self) -> bool {
1479 self.0.exit_ok().is_ok()
1482 /// Returns the exit code of the process, if any.
1484 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1485 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1486 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1487 /// runtime system (often, for example, 255, 254, 127 or 126).
1489 /// On Unix, this will return `None` if the process was terminated by a signal.
1490 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1491 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1496 /// use std::process::Command;
1498 /// let status = Command::new("mkdir")
1499 /// .arg("projects")
1501 /// .expect("failed to execute mkdir");
1503 /// match status.code() {
1504 /// Some(code) => println!("Exited with status code: {}", code),
1505 /// None => println!("Process terminated by signal")
1509 #[stable(feature = "process", since = "1.0.0")]
1510 pub fn code(&self) -> Option<i32> {
1515 impl AsInner<imp::ExitStatus> for ExitStatus {
1516 fn as_inner(&self) -> &imp::ExitStatus {
1521 impl FromInner<imp::ExitStatus> for ExitStatus {
1522 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1527 #[stable(feature = "process", since = "1.0.0")]
1528 impl fmt::Display for ExitStatus {
1529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1534 /// Allows extension traits within `std`.
1535 #[unstable(feature = "sealed", issue = "none")]
1536 impl crate::sealed::Sealed for ExitStatusError {}
1538 /// Describes the result of a process after it has failed
1540 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1545 /// #![feature(exit_status_error)]
1546 /// # if cfg!(unix) {
1547 /// use std::process::{Command, ExitStatusError};
1549 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1550 /// Command::new(cmd).status().unwrap().exit_ok()?;
1554 /// run("true").unwrap();
1555 /// run("false").unwrap_err();
1556 /// # } // cfg!(unix)
1558 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1559 #[unstable(feature = "exit_status_error", issue = "84908")]
1560 // The definition of imp::ExitStatusError should ideally be such that
1561 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1562 pub struct ExitStatusError(imp::ExitStatusError);
1564 #[unstable(feature = "exit_status_error", issue = "84908")]
1565 impl ExitStatusError {
1566 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1568 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1569 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1570 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1571 /// runtime system (often, for example, 255, 254, 127 or 126).
1573 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1574 /// handle such situations specially, consider using methods from
1575 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1577 /// If the process finished by calling `exit` with a nonzero value, this will return
1578 /// that exit status.
1580 /// If the error was something else, it will return `None`.
1582 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1583 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1588 /// #![feature(exit_status_error)]
1589 /// # #[cfg(unix)] {
1590 /// use std::process::Command;
1592 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1593 /// assert_eq!(bad.code(), Some(1));
1594 /// # } // #[cfg(unix)]
1597 pub fn code(&self) -> Option<i32> {
1598 self.code_nonzero().map(Into::into)
1601 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1603 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1605 /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1606 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1607 /// a type-level guarantee of nonzeroness.
1612 /// #![feature(exit_status_error)]
1613 /// # if cfg!(unix) {
1614 /// use std::convert::TryFrom;
1615 /// use std::num::NonZeroI32;
1616 /// use std::process::Command;
1618 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1619 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1620 /// # } // cfg!(unix)
1623 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1627 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1629 pub fn into_status(&self) -> ExitStatus {
1630 ExitStatus(self.0.into())
1634 #[unstable(feature = "exit_status_error", issue = "84908")]
1635 impl Into<ExitStatus> for ExitStatusError {
1636 fn into(self) -> ExitStatus {
1637 ExitStatus(self.0.into())
1641 #[unstable(feature = "exit_status_error", issue = "84908")]
1642 impl fmt::Display for ExitStatusError {
1643 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1644 write!(f, "process exited unsuccessfully: {}", self.into_status())
1648 #[unstable(feature = "exit_status_error", issue = "84908")]
1649 impl crate::error::Error for ExitStatusError {}
1651 /// This type represents the status code a process can return to its
1652 /// parent under normal termination.
1654 /// Numeric values used in this type don't have portable meanings, and
1655 /// different platforms may mask different amounts of them.
1657 /// For the platform's canonical successful and unsuccessful codes, see
1658 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1660 /// [`SUCCESS`]: ExitCode::SUCCESS
1661 /// [`FAILURE`]: ExitCode::FAILURE
1663 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1664 /// it was ultimately cut from that RFC, and thus this type is more subject
1665 /// to change even than the usual unstable item churn.
1667 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1668 #[derive(Clone, Copy, Debug)]
1669 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1670 pub struct ExitCode(imp::ExitCode);
1672 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1674 /// The canonical ExitCode for successful termination on this platform.
1676 /// Note that a `()`-returning `main` implicitly results in a successful
1677 /// termination, so there's no need to return this from `main` unless
1678 /// you're also returning other possible codes.
1679 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1680 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1682 /// The canonical ExitCode for unsuccessful termination on this platform.
1684 /// If you're only returning this and `SUCCESS` from `main`, consider
1685 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1686 /// return the same codes (but will also `eprintln!` the error).
1687 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1688 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1692 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1693 /// error is returned.
1695 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1697 /// This is equivalent to sending a SIGKILL on Unix platforms.
1704 /// use std::process::Command;
1706 /// let mut command = Command::new("yes");
1707 /// if let Ok(mut child) = command.spawn() {
1708 /// child.kill().expect("command wasn't running");
1710 /// println!("yes command didn't start");
1714 /// [`ErrorKind`]: io::ErrorKind
1715 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1716 #[stable(feature = "process", since = "1.0.0")]
1717 pub fn kill(&mut self) -> io::Result<()> {
1721 /// Returns the OS-assigned process identifier associated with this child.
1728 /// use std::process::Command;
1730 /// let mut command = Command::new("ls");
1731 /// if let Ok(child) = command.spawn() {
1732 /// println!("Child's ID is {}", child.id());
1734 /// println!("ls command didn't start");
1738 #[stable(feature = "process_id", since = "1.3.0")]
1739 pub fn id(&self) -> u32 {
1743 /// Waits for the child to exit completely, returning the status that it
1744 /// exited with. This function will continue to have the same return value
1745 /// after it has been called at least once.
1747 /// The stdin handle to the child process, if any, will be closed
1748 /// before waiting. This helps avoid deadlock: it ensures that the
1749 /// child does not block waiting for input from the parent, while
1750 /// the parent waits for the child to exit.
1757 /// use std::process::Command;
1759 /// let mut command = Command::new("ls");
1760 /// if let Ok(mut child) = command.spawn() {
1761 /// child.wait().expect("command wasn't running");
1762 /// println!("Child has finished its execution!");
1764 /// println!("ls command didn't start");
1767 #[stable(feature = "process", since = "1.0.0")]
1768 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1769 drop(self.stdin.take());
1770 self.handle.wait().map(ExitStatus)
1773 /// Attempts to collect the exit status of the child if it has already
1776 /// This function will not block the calling thread and will only
1777 /// check to see if the child process has exited or not. If the child has
1778 /// exited then on Unix the process ID is reaped. This function is
1779 /// guaranteed to repeatedly return a successful exit status so long as the
1780 /// child has already exited.
1782 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1783 /// exit status is not available at this time then `Ok(None)` is returned.
1784 /// If an error occurs, then that error is returned.
1786 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1793 /// use std::process::Command;
1795 /// let mut child = Command::new("ls").spawn().unwrap();
1797 /// match child.try_wait() {
1798 /// Ok(Some(status)) => println!("exited with: {}", status),
1800 /// println!("status not ready yet, let's really wait");
1801 /// let res = child.wait();
1802 /// println!("result: {:?}", res);
1804 /// Err(e) => println!("error attempting to wait: {}", e),
1807 #[stable(feature = "process_try_wait", since = "1.18.0")]
1808 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1809 Ok(self.handle.try_wait()?.map(ExitStatus))
1812 /// Simultaneously waits for the child to exit and collect all remaining
1813 /// output on the stdout/stderr handles, returning an `Output`
1816 /// The stdin handle to the child process, if any, will be closed
1817 /// before waiting. This helps avoid deadlock: it ensures that the
1818 /// child does not block waiting for input from the parent, while
1819 /// the parent waits for the child to exit.
1821 /// By default, stdin, stdout and stderr are inherited from the parent.
1822 /// In order to capture the output into this `Result<Output>` it is
1823 /// necessary to create new pipes between parent and child. Use
1824 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1829 /// use std::process::{Command, Stdio};
1831 /// let child = Command::new("/bin/cat")
1832 /// .arg("file.txt")
1833 /// .stdout(Stdio::piped())
1835 /// .expect("failed to execute child");
1837 /// let output = child
1838 /// .wait_with_output()
1839 /// .expect("failed to wait on child");
1841 /// assert!(output.status.success());
1844 #[stable(feature = "process", since = "1.0.0")]
1845 pub fn wait_with_output(mut self) -> io::Result<Output> {
1846 drop(self.stdin.take());
1848 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1849 match (self.stdout.take(), self.stderr.take()) {
1851 (Some(mut out), None) => {
1852 let res = out.read_to_end(&mut stdout);
1855 (None, Some(mut err)) => {
1856 let res = err.read_to_end(&mut stderr);
1859 (Some(out), Some(err)) => {
1860 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1865 let status = self.wait()?;
1866 Ok(Output { status, stdout, stderr })
1870 /// Terminates the current process with the specified exit code.
1872 /// This function will never return and will immediately terminate the current
1873 /// process. The exit code is passed through to the underlying OS and will be
1874 /// available for consumption by another process.
1876 /// Note that because this function never returns, and that it terminates the
1877 /// process, no destructors on the current stack or any other thread's stack
1878 /// will be run. If a clean shutdown is needed it is recommended to only call
1879 /// this function at a known point where there are no more destructors left
1882 /// ## Platform-specific behavior
1884 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1885 /// will be visible to a parent process inspecting the exit code. On most
1886 /// Unix-like platforms, only the eight least-significant bits are considered.
1890 /// Due to this function’s behavior regarding destructors, a conventional way
1891 /// to use the function is to extract the actual computation to another
1892 /// function and compute the exit code from its return value:
1895 /// fn run_app() -> Result<(), ()> {
1896 /// // Application logic here
1901 /// std::process::exit(match run_app() {
1904 /// eprintln!("error: {:?}", err);
1911 /// Due to [platform-specific behavior], the exit code for this example will be
1912 /// `0` on Linux, but `256` on Windows:
1915 /// use std::process;
1917 /// process::exit(0x0100);
1920 /// [platform-specific behavior]: #platform-specific-behavior
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 pub fn exit(code: i32) -> ! {
1923 crate::rt::cleanup();
1924 crate::sys::os::exit(code)
1927 /// Terminates the process in an abnormal fashion.
1929 /// The function will never return and will immediately terminate the current
1930 /// process in a platform specific "abnormal" manner.
1932 /// Note that because this function never returns, and that it terminates the
1933 /// process, no destructors on the current stack or any other thread's stack
1936 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
1937 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
1939 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1940 /// the current thread's stack and calls all destructors.
1941 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1942 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1943 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1945 /// If a clean shutdown is needed it is recommended to only call
1946 /// this function at a known point where there are no more destructors left
1949 /// The process's termination will be similar to that from the C `abort()`
1950 /// function. On Unix, the process will terminate with signal `SIGABRT`, which
1951 /// typically means that the shell prints "Aborted".
1956 /// use std::process;
1959 /// println!("aborting");
1961 /// process::abort();
1963 /// // execution never gets here
1967 /// The `abort` function terminates the process, so the destructor will not
1968 /// get run on the example below:
1971 /// use std::process;
1975 /// impl Drop for HasDrop {
1976 /// fn drop(&mut self) {
1977 /// println!("This will never be printed!");
1982 /// let _x = HasDrop;
1983 /// process::abort();
1984 /// // the destructor implemented for HasDrop will never get run
1988 /// [panic hook]: crate::panic::set_hook
1989 #[stable(feature = "process_abort", since = "1.17.0")]
1991 pub fn abort() -> ! {
1992 crate::sys::abort_internal();
1995 /// Returns the OS-assigned process identifier associated with this process.
2002 /// use std::process;
2004 /// println!("My pid is {}", process::id());
2009 #[stable(feature = "getpid", since = "1.26.0")]
2010 pub fn id() -> u32 {
2011 crate::sys::os::getpid()
2014 /// A trait for implementing arbitrary return types in the `main` function.
2016 /// The C-main function only supports to return integers as return type.
2017 /// So, every type implementing the `Termination` trait has to be converted
2020 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2021 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2022 #[cfg_attr(not(test), lang = "termination")]
2023 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2024 #[rustc_on_unimplemented(
2025 message = "`main` has invalid return type `{Self}`",
2026 label = "`main` can only return types that implement `{Termination}`"
2028 pub trait Termination {
2029 /// Is called to get the representation of the value as status code.
2030 /// This status code is returned to the operating system.
2031 fn report(self) -> i32;
2034 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2035 impl Termination for () {
2037 fn report(self) -> i32 {
2038 ExitCode::SUCCESS.report()
2042 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2043 impl<E: fmt::Debug> Termination for Result<(), E> {
2044 fn report(self) -> i32 {
2046 Ok(()) => ().report(),
2047 Err(err) => Err::<!, _>(err).report(),
2052 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2053 impl Termination for ! {
2054 fn report(self) -> i32 {
2059 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2060 impl<E: fmt::Debug> Termination for Result<!, E> {
2061 fn report(self) -> i32 {
2062 let Err(err) = self;
2063 eprintln!("Error: {:?}", err);
2064 ExitCode::FAILURE.report()
2068 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2069 impl Termination for ExitCode {
2071 fn report(self) -> i32 {