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 #[unstable(feature = "command_access", issue = "44434")]
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 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 impl AsInner<imp::Process> for Child {
209 fn as_inner(&self) -> &imp::Process {
214 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
215 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
218 stdin: io.stdin.map(ChildStdin::from_inner),
219 stdout: io.stdout.map(ChildStdout::from_inner),
220 stderr: io.stderr.map(ChildStderr::from_inner),
225 impl IntoInner<imp::Process> for Child {
226 fn into_inner(self) -> imp::Process {
231 #[stable(feature = "std_debug", since = "1.16.0")]
232 impl fmt::Debug for Child {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 f.debug_struct("Child")
235 .field("stdin", &self.stdin)
236 .field("stdout", &self.stdout)
237 .field("stderr", &self.stderr)
238 .finish_non_exhaustive()
242 /// A handle to a child process's standard input (stdin).
244 /// This struct is used in the [`stdin`] field on [`Child`].
246 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
247 /// file handle will be closed. If the child process was blocked on input prior
248 /// to being dropped, it will become unblocked after dropping.
250 /// [`stdin`]: Child::stdin
252 #[stable(feature = "process", since = "1.0.0")]
253 pub struct ChildStdin {
257 #[stable(feature = "process", since = "1.0.0")]
258 impl Write for ChildStdin {
259 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
263 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
264 (&*self).write_vectored(bufs)
267 fn is_write_vectored(&self) -> bool {
268 io::Write::is_write_vectored(&&*self)
271 fn flush(&mut self) -> io::Result<()> {
276 #[stable(feature = "write_mt", since = "1.48.0")]
277 impl Write for &ChildStdin {
278 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
279 self.inner.write(buf)
282 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
283 self.inner.write_vectored(bufs)
286 fn is_write_vectored(&self) -> bool {
287 self.inner.is_write_vectored()
290 fn flush(&mut self) -> io::Result<()> {
295 impl AsInner<AnonPipe> for ChildStdin {
296 fn as_inner(&self) -> &AnonPipe {
301 impl IntoInner<AnonPipe> for ChildStdin {
302 fn into_inner(self) -> AnonPipe {
307 impl FromInner<AnonPipe> for ChildStdin {
308 fn from_inner(pipe: AnonPipe) -> ChildStdin {
309 ChildStdin { inner: pipe }
313 #[stable(feature = "std_debug", since = "1.16.0")]
314 impl fmt::Debug for ChildStdin {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 f.debug_struct("ChildStdin").finish_non_exhaustive()
320 /// A handle to a child process's standard output (stdout).
322 /// This struct is used in the [`stdout`] field on [`Child`].
324 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
325 /// underlying file handle will be closed.
327 /// [`stdout`]: Child::stdout
329 #[stable(feature = "process", since = "1.0.0")]
330 pub struct ChildStdout {
334 #[stable(feature = "process", since = "1.0.0")]
335 impl Read for ChildStdout {
336 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
340 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
341 self.inner.read_vectored(bufs)
345 fn is_read_vectored(&self) -> bool {
346 self.inner.is_read_vectored()
350 unsafe fn initializer(&self) -> Initializer {
351 // SAFETY: Read is guaranteed to work on uninitialized memory
352 unsafe { Initializer::nop() }
356 impl AsInner<AnonPipe> for ChildStdout {
357 fn as_inner(&self) -> &AnonPipe {
362 impl IntoInner<AnonPipe> for ChildStdout {
363 fn into_inner(self) -> AnonPipe {
368 impl FromInner<AnonPipe> for ChildStdout {
369 fn from_inner(pipe: AnonPipe) -> ChildStdout {
370 ChildStdout { inner: pipe }
374 #[stable(feature = "std_debug", since = "1.16.0")]
375 impl fmt::Debug for ChildStdout {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 f.debug_struct("ChildStdout").finish_non_exhaustive()
381 /// A handle to a child process's stderr.
383 /// This struct is used in the [`stderr`] field on [`Child`].
385 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
386 /// underlying file handle will be closed.
388 /// [`stderr`]: Child::stderr
390 #[stable(feature = "process", since = "1.0.0")]
391 pub struct ChildStderr {
395 #[stable(feature = "process", since = "1.0.0")]
396 impl Read for ChildStderr {
397 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
401 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
402 self.inner.read_vectored(bufs)
406 fn is_read_vectored(&self) -> bool {
407 self.inner.is_read_vectored()
411 unsafe fn initializer(&self) -> Initializer {
412 // SAFETY: Read is guaranteed to work on uninitialized memory
413 unsafe { Initializer::nop() }
417 impl AsInner<AnonPipe> for ChildStderr {
418 fn as_inner(&self) -> &AnonPipe {
423 impl IntoInner<AnonPipe> for ChildStderr {
424 fn into_inner(self) -> AnonPipe {
429 impl FromInner<AnonPipe> for ChildStderr {
430 fn from_inner(pipe: AnonPipe) -> ChildStderr {
431 ChildStderr { inner: pipe }
435 #[stable(feature = "std_debug", since = "1.16.0")]
436 impl fmt::Debug for ChildStderr {
437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438 f.debug_struct("ChildStderr").finish_non_exhaustive()
442 /// A process builder, providing fine-grained control
443 /// over how a new process should be spawned.
445 /// A default configuration can be
446 /// generated using `Command::new(program)`, where `program` gives a path to the
447 /// program to be executed. Additional builder methods allow the configuration
448 /// to be changed (for example, by adding arguments) prior to spawning:
451 /// use std::process::Command;
453 /// let output = if cfg!(target_os = "windows") {
454 /// Command::new("cmd")
455 /// .args(["/C", "echo hello"])
457 /// .expect("failed to execute process")
459 /// Command::new("sh")
461 /// .arg("echo hello")
463 /// .expect("failed to execute process")
466 /// let hello = output.stdout;
469 /// `Command` can be reused to spawn multiple processes. The builder methods
470 /// change the command without needing to immediately spawn the process.
473 /// use std::process::Command;
475 /// let mut echo_hello = Command::new("sh");
476 /// echo_hello.arg("-c")
477 /// .arg("echo hello");
478 /// let hello_1 = echo_hello.output().expect("failed to execute process");
479 /// let hello_2 = echo_hello.output().expect("failed to execute process");
482 /// Similarly, you can call builder methods after spawning a process and then
483 /// spawn a new process with the modified settings.
486 /// use std::process::Command;
488 /// let mut list_dir = Command::new("ls");
490 /// // Execute `ls` in the current directory of the program.
491 /// list_dir.status().expect("process failed to execute");
495 /// // Change `ls` to execute in the root directory.
496 /// list_dir.current_dir("/");
498 /// // And then execute `ls` again but in the root directory.
499 /// list_dir.status().expect("process failed to execute");
501 #[stable(feature = "process", since = "1.0.0")]
506 /// Allows extension traits within `std`.
507 #[unstable(feature = "sealed", issue = "none")]
508 impl crate::sealed::Sealed for Command {}
511 /// Constructs a new `Command` for launching the program at
512 /// path `program`, with the following default configuration:
514 /// * No arguments to the program
515 /// * Inherit the current process's environment
516 /// * Inherit the current process's working directory
517 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
519 /// Builder methods are provided to change these defaults and
520 /// otherwise configure the process.
522 /// If `program` is not an absolute path, the `PATH` will be searched in
523 /// an OS-defined way.
525 /// The search path to be used may be controlled by setting the
526 /// `PATH` environment variable on the Command,
527 /// but this has some implementation limitations on Windows
528 /// (see issue #37519).
535 /// use std::process::Command;
537 /// Command::new("sh")
539 /// .expect("sh command failed to start");
541 #[stable(feature = "process", since = "1.0.0")]
542 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
543 Command { inner: imp::Command::new(program.as_ref()) }
546 /// Adds an argument to pass to the program.
548 /// Only one argument can be passed per use. So instead of:
551 /// # std::process::Command::new("sh")
552 /// .arg("-C /path/to/repo")
559 /// # std::process::Command::new("sh")
561 /// .arg("/path/to/repo")
565 /// To pass multiple arguments see [`args`].
567 /// [`args`]: Command::args
569 /// Note that the argument is not passed through a shell, but given
570 /// literally to the program. This means that shell syntax like quotes,
571 /// escaped characters, word splitting, glob patterns, substitution, etc.
579 /// use std::process::Command;
581 /// Command::new("ls")
585 /// .expect("ls command failed to start");
587 #[stable(feature = "process", since = "1.0.0")]
588 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
589 self.inner.arg(arg.as_ref());
593 /// Adds multiple arguments to pass to the program.
595 /// To pass a single argument see [`arg`].
597 /// [`arg`]: Command::arg
599 /// Note that the arguments are not passed through a shell, but given
600 /// literally to the program. This means that shell syntax like quotes,
601 /// escaped characters, word splitting, glob patterns, substitution, etc.
609 /// use std::process::Command;
611 /// Command::new("ls")
612 /// .args(["-l", "-a"])
614 /// .expect("ls command failed to start");
616 #[stable(feature = "process", since = "1.0.0")]
617 pub fn args<I, S>(&mut self, args: I) -> &mut Command
619 I: IntoIterator<Item = S>,
623 self.arg(arg.as_ref());
628 /// Inserts or updates an environment variable mapping.
630 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
631 /// and case-sensitive on all other platforms.
638 /// use std::process::Command;
640 /// Command::new("ls")
641 /// .env("PATH", "/bin")
643 /// .expect("ls command failed to start");
645 #[stable(feature = "process", since = "1.0.0")]
646 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
651 self.inner.env_mut().set(key.as_ref(), val.as_ref());
655 /// Adds or updates multiple environment variable mappings.
662 /// use std::process::{Command, Stdio};
664 /// use std::collections::HashMap;
666 /// let filtered_env : HashMap<String, String> =
667 /// env::vars().filter(|&(ref k, _)|
668 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
671 /// Command::new("printenv")
672 /// .stdin(Stdio::null())
673 /// .stdout(Stdio::inherit())
675 /// .envs(&filtered_env)
677 /// .expect("printenv failed to start");
679 #[stable(feature = "command_envs", since = "1.19.0")]
680 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
682 I: IntoIterator<Item = (K, V)>,
686 for (ref key, ref val) in vars {
687 self.inner.env_mut().set(key.as_ref(), val.as_ref());
692 /// Removes an environment variable mapping.
699 /// use std::process::Command;
701 /// Command::new("ls")
702 /// .env_remove("PATH")
704 /// .expect("ls command failed to start");
706 #[stable(feature = "process", since = "1.0.0")]
707 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
708 self.inner.env_mut().remove(key.as_ref());
712 /// Clears the entire environment map for the child process.
719 /// use std::process::Command;
721 /// Command::new("ls")
724 /// .expect("ls command failed to start");
726 #[stable(feature = "process", since = "1.0.0")]
727 pub fn env_clear(&mut self) -> &mut Command {
728 self.inner.env_mut().clear();
732 /// Sets the working directory for the child process.
734 /// # Platform-specific behavior
736 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
737 /// whether it should be interpreted relative to the parent's working
738 /// directory or relative to `current_dir`. The behavior in this case is
739 /// platform specific and unstable, and it's recommended to use
740 /// [`canonicalize`] to get an absolute program path instead.
747 /// use std::process::Command;
749 /// Command::new("ls")
750 /// .current_dir("/bin")
752 /// .expect("ls command failed to start");
755 /// [`canonicalize`]: crate::fs::canonicalize
756 #[stable(feature = "process", since = "1.0.0")]
757 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
758 self.inner.cwd(dir.as_ref().as_ref());
762 /// Configuration for the child process's standard input (stdin) handle.
764 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
765 /// defaults to [`piped`] when used with `output`.
767 /// [`inherit`]: Stdio::inherit
768 /// [`piped`]: Stdio::piped
775 /// use std::process::{Command, Stdio};
777 /// Command::new("ls")
778 /// .stdin(Stdio::null())
780 /// .expect("ls command failed to start");
782 #[stable(feature = "process", since = "1.0.0")]
783 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
784 self.inner.stdin(cfg.into().0);
788 /// Configuration for the child process's standard output (stdout) handle.
790 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
791 /// defaults to [`piped`] when used with `output`.
793 /// [`inherit`]: Stdio::inherit
794 /// [`piped`]: Stdio::piped
801 /// use std::process::{Command, Stdio};
803 /// Command::new("ls")
804 /// .stdout(Stdio::null())
806 /// .expect("ls command failed to start");
808 #[stable(feature = "process", since = "1.0.0")]
809 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
810 self.inner.stdout(cfg.into().0);
814 /// Configuration for the child process's standard error (stderr) handle.
816 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
817 /// defaults to [`piped`] when used with `output`.
819 /// [`inherit`]: Stdio::inherit
820 /// [`piped`]: Stdio::piped
827 /// use std::process::{Command, Stdio};
829 /// Command::new("ls")
830 /// .stderr(Stdio::null())
832 /// .expect("ls command failed to start");
834 #[stable(feature = "process", since = "1.0.0")]
835 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
836 self.inner.stderr(cfg.into().0);
840 /// Executes the command as a child process, returning a handle to it.
842 /// By default, stdin, stdout and stderr are inherited from the parent.
849 /// use std::process::Command;
851 /// Command::new("ls")
853 /// .expect("ls command failed to start");
855 #[stable(feature = "process", since = "1.0.0")]
856 pub fn spawn(&mut self) -> io::Result<Child> {
857 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
860 /// Executes the command as a child process, waiting for it to finish and
861 /// collecting all of its output.
863 /// By default, stdout and stderr are captured (and used to provide the
864 /// resulting output). Stdin is not inherited from the parent and any
865 /// attempt by the child process to read from the stdin stream will result
866 /// in the stream immediately closing.
871 /// use std::process::Command;
872 /// use std::io::{self, Write};
873 /// let output = Command::new("/bin/cat")
876 /// .expect("failed to execute process");
878 /// println!("status: {}", output.status);
879 /// io::stdout().write_all(&output.stdout).unwrap();
880 /// io::stderr().write_all(&output.stderr).unwrap();
882 /// assert!(output.status.success());
884 #[stable(feature = "process", since = "1.0.0")]
885 pub fn output(&mut self) -> io::Result<Output> {
887 .spawn(imp::Stdio::MakePipe, false)
888 .map(Child::from_inner)
889 .and_then(|p| p.wait_with_output())
892 /// Executes a command as a child process, waiting for it to finish and
893 /// collecting its status.
895 /// By default, stdin, stdout and stderr are inherited from the parent.
900 /// use std::process::Command;
902 /// let status = Command::new("/bin/cat")
905 /// .expect("failed to execute process");
907 /// println!("process finished with: {}", status);
909 /// assert!(status.success());
911 #[stable(feature = "process", since = "1.0.0")]
912 pub fn status(&mut self) -> io::Result<ExitStatus> {
914 .spawn(imp::Stdio::Inherit, true)
915 .map(Child::from_inner)
916 .and_then(|mut p| p.wait())
919 /// Returns the path to the program that was given to [`Command::new`].
924 /// # #![feature(command_access)]
925 /// use std::process::Command;
927 /// let cmd = Command::new("echo");
928 /// assert_eq!(cmd.get_program(), "echo");
930 #[unstable(feature = "command_access", issue = "44434")]
931 pub fn get_program(&self) -> &OsStr {
932 self.inner.get_program()
935 /// Returns an iterator of the arguments that will be passed to the program.
937 /// This does not include the path to the program as the first argument;
938 /// it only includes the arguments specified with [`Command::arg`] and
939 /// [`Command::args`].
944 /// # #![feature(command_access)]
945 /// use std::ffi::OsStr;
946 /// use std::process::Command;
948 /// let mut cmd = Command::new("echo");
949 /// cmd.arg("first").arg("second");
950 /// let args: Vec<&OsStr> = cmd.get_args().collect();
951 /// assert_eq!(args, &["first", "second"]);
953 #[unstable(feature = "command_access", issue = "44434")]
954 pub fn get_args(&self) -> CommandArgs<'_> {
955 CommandArgs { inner: self.inner.get_args() }
958 /// Returns an iterator of the environment variables that will be set when
959 /// the process is spawned.
961 /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
962 /// value is the key, and the second is the value, which is [`None`] if
963 /// the environment variable is to be explicitly removed.
965 /// This only includes environment variables explicitly set with
966 /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
967 /// does not include environment variables that will be inherited by the
973 /// # #![feature(command_access)]
974 /// use std::ffi::OsStr;
975 /// use std::process::Command;
977 /// let mut cmd = Command::new("ls");
978 /// cmd.env("TERM", "dumb").env_remove("TZ");
979 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
980 /// assert_eq!(envs, &[
981 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
982 /// (OsStr::new("TZ"), None)
985 #[unstable(feature = "command_access", issue = "44434")]
986 pub fn get_envs(&self) -> CommandEnvs<'_> {
987 self.inner.get_envs()
990 /// Returns the working directory for the child process.
992 /// This returns [`None`] if the working directory will not be changed.
997 /// # #![feature(command_access)]
998 /// use std::path::Path;
999 /// use std::process::Command;
1001 /// let mut cmd = Command::new("ls");
1002 /// assert_eq!(cmd.get_current_dir(), None);
1003 /// cmd.current_dir("/bin");
1004 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1006 #[unstable(feature = "command_access", issue = "44434")]
1007 pub fn get_current_dir(&self) -> Option<&Path> {
1008 self.inner.get_current_dir()
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl fmt::Debug for Command {
1014 /// Format the program and arguments of a Command for display. Any
1015 /// non-utf8 data is lossily converted using the utf8 replacement
1017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1022 impl AsInner<imp::Command> for Command {
1023 fn as_inner(&self) -> &imp::Command {
1028 impl AsInnerMut<imp::Command> for Command {
1029 fn as_inner_mut(&mut self) -> &mut imp::Command {
1034 /// An iterator over the command arguments.
1036 /// This struct is created by [`Command::get_args`]. See its documentation for
1038 #[unstable(feature = "command_access", issue = "44434")]
1040 pub struct CommandArgs<'a> {
1041 inner: imp::CommandArgs<'a>,
1044 #[unstable(feature = "command_access", issue = "44434")]
1045 impl<'a> Iterator for CommandArgs<'a> {
1046 type Item = &'a OsStr;
1047 fn next(&mut self) -> Option<&'a OsStr> {
1050 fn size_hint(&self) -> (usize, Option<usize>) {
1051 self.inner.size_hint()
1055 #[unstable(feature = "command_access", issue = "44434")]
1056 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1057 fn len(&self) -> usize {
1060 fn is_empty(&self) -> bool {
1061 self.inner.is_empty()
1065 /// The output of a finished process.
1067 /// This is returned in a Result by either the [`output`] method of a
1068 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1071 /// [`output`]: Command::output
1072 /// [`wait_with_output`]: Child::wait_with_output
1073 #[derive(PartialEq, Eq, Clone)]
1074 #[stable(feature = "process", since = "1.0.0")]
1076 /// The status (exit code) of the process.
1077 #[stable(feature = "process", since = "1.0.0")]
1078 pub status: ExitStatus,
1079 /// The data that the process wrote to stdout.
1080 #[stable(feature = "process", since = "1.0.0")]
1081 pub stdout: Vec<u8>,
1082 /// The data that the process wrote to stderr.
1083 #[stable(feature = "process", since = "1.0.0")]
1084 pub stderr: Vec<u8>,
1087 // If either stderr or stdout are valid utf8 strings it prints the valid
1088 // strings, otherwise it prints the byte sequence instead
1089 #[stable(feature = "process_output_debug", since = "1.7.0")]
1090 impl fmt::Debug for Output {
1091 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1092 let stdout_utf8 = str::from_utf8(&self.stdout);
1093 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1095 Err(_) => &self.stdout,
1098 let stderr_utf8 = str::from_utf8(&self.stderr);
1099 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1101 Err(_) => &self.stderr,
1104 fmt.debug_struct("Output")
1105 .field("status", &self.status)
1106 .field("stdout", stdout_debug)
1107 .field("stderr", stderr_debug)
1112 /// Describes what to do with a standard I/O stream for a child process when
1113 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1115 /// [`stdin`]: Command::stdin
1116 /// [`stdout`]: Command::stdout
1117 /// [`stderr`]: Command::stderr
1118 #[stable(feature = "process", since = "1.0.0")]
1119 pub struct Stdio(imp::Stdio);
1122 /// A new pipe should be arranged to connect the parent and child processes.
1129 /// use std::process::{Command, Stdio};
1131 /// let output = Command::new("echo")
1132 /// .arg("Hello, world!")
1133 /// .stdout(Stdio::piped())
1135 /// .expect("Failed to execute command");
1137 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1138 /// // Nothing echoed to console
1144 /// use std::io::Write;
1145 /// use std::process::{Command, Stdio};
1147 /// let mut child = Command::new("rev")
1148 /// .stdin(Stdio::piped())
1149 /// .stdout(Stdio::piped())
1151 /// .expect("Failed to spawn child process");
1153 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1154 /// std::thread::spawn(move || {
1155 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1158 /// let output = child.wait_with_output().expect("Failed to read stdout");
1159 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1162 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1163 /// stdout and stderr at the same time may cause a deadlock.
1164 /// This is an issue when running any program that doesn't guarantee that it reads
1165 /// its entire stdin before writing more than a pipe buffer's worth of output.
1166 /// The size of a pipe buffer varies on different targets.
1168 #[stable(feature = "process", since = "1.0.0")]
1169 pub fn piped() -> Stdio {
1170 Stdio(imp::Stdio::MakePipe)
1173 /// The child inherits from the corresponding parent descriptor.
1180 /// use std::process::{Command, Stdio};
1182 /// let output = Command::new("echo")
1183 /// .arg("Hello, world!")
1184 /// .stdout(Stdio::inherit())
1186 /// .expect("Failed to execute command");
1188 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1189 /// // "Hello, world!" echoed to console
1195 /// use std::process::{Command, Stdio};
1196 /// use std::io::{self, Write};
1198 /// let output = Command::new("rev")
1199 /// .stdin(Stdio::inherit())
1200 /// .stdout(Stdio::piped())
1202 /// .expect("Failed to execute command");
1204 /// print!("You piped in the reverse of: ");
1205 /// io::stdout().write_all(&output.stdout).unwrap();
1207 #[stable(feature = "process", since = "1.0.0")]
1208 pub fn inherit() -> Stdio {
1209 Stdio(imp::Stdio::Inherit)
1212 /// This stream will be ignored. This is the equivalent of attaching the
1213 /// stream to `/dev/null`.
1220 /// use std::process::{Command, Stdio};
1222 /// let output = Command::new("echo")
1223 /// .arg("Hello, world!")
1224 /// .stdout(Stdio::null())
1226 /// .expect("Failed to execute command");
1228 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1229 /// // Nothing echoed to console
1235 /// use std::process::{Command, Stdio};
1237 /// let output = Command::new("rev")
1238 /// .stdin(Stdio::null())
1239 /// .stdout(Stdio::piped())
1241 /// .expect("Failed to execute command");
1243 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1244 /// // Ignores any piped-in input
1246 #[stable(feature = "process", since = "1.0.0")]
1247 pub fn null() -> Stdio {
1248 Stdio(imp::Stdio::Null)
1252 impl FromInner<imp::Stdio> for Stdio {
1253 fn from_inner(inner: imp::Stdio) -> Stdio {
1258 #[stable(feature = "std_debug", since = "1.16.0")]
1259 impl fmt::Debug for Stdio {
1260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261 f.debug_struct("Stdio").finish_non_exhaustive()
1265 #[stable(feature = "stdio_from", since = "1.20.0")]
1266 impl From<ChildStdin> for Stdio {
1267 /// Converts a `ChildStdin` into a `Stdio`
1271 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1274 /// use std::process::{Command, Stdio};
1276 /// let reverse = Command::new("rev")
1277 /// .stdin(Stdio::piped())
1279 /// .expect("failed reverse command");
1281 /// let _echo = Command::new("echo")
1282 /// .arg("Hello, world!")
1283 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1285 /// .expect("failed echo command");
1287 /// // "!dlrow ,olleH" echoed to console
1289 fn from(child: ChildStdin) -> Stdio {
1290 Stdio::from_inner(child.into_inner().into())
1294 #[stable(feature = "stdio_from", since = "1.20.0")]
1295 impl From<ChildStdout> for Stdio {
1296 /// Converts a `ChildStdout` into a `Stdio`
1300 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1303 /// use std::process::{Command, Stdio};
1305 /// let hello = Command::new("echo")
1306 /// .arg("Hello, world!")
1307 /// .stdout(Stdio::piped())
1309 /// .expect("failed echo command");
1311 /// let reverse = Command::new("rev")
1312 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1314 /// .expect("failed reverse command");
1316 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1318 fn from(child: ChildStdout) -> Stdio {
1319 Stdio::from_inner(child.into_inner().into())
1323 #[stable(feature = "stdio_from", since = "1.20.0")]
1324 impl From<ChildStderr> for Stdio {
1325 /// Converts a `ChildStderr` into a `Stdio`
1330 /// use std::process::{Command, Stdio};
1332 /// let reverse = Command::new("rev")
1333 /// .arg("non_existing_file.txt")
1334 /// .stderr(Stdio::piped())
1336 /// .expect("failed reverse command");
1338 /// let cat = Command::new("cat")
1340 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1342 /// .expect("failed echo command");
1345 /// String::from_utf8_lossy(&cat.stdout),
1346 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1349 fn from(child: ChildStderr) -> Stdio {
1350 Stdio::from_inner(child.into_inner().into())
1354 #[stable(feature = "stdio_from", since = "1.20.0")]
1355 impl From<fs::File> for Stdio {
1356 /// Converts a `File` into a `Stdio`
1360 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1363 /// use std::fs::File;
1364 /// use std::process::Command;
1366 /// // With the `foo.txt` file containing `Hello, world!"
1367 /// let file = File::open("foo.txt").unwrap();
1369 /// let reverse = Command::new("rev")
1370 /// .stdin(file) // Implicit File conversion into a Stdio
1372 /// .expect("failed reverse command");
1374 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1376 fn from(file: fs::File) -> Stdio {
1377 Stdio::from_inner(file.into_inner().into())
1381 /// Describes the result of a process after it has terminated.
1383 /// This `struct` is used to represent the exit status or other termination of a child process.
1384 /// Child processes are created via the [`Command`] struct and their exit
1385 /// status is exposed through the [`status`] method, or the [`wait`] method
1386 /// of a [`Child`] process.
1388 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1389 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1391 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1392 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1394 /// [`status`]: Command::status
1395 /// [`wait`]: Child::wait
1396 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1397 #[stable(feature = "process", since = "1.0.0")]
1398 pub struct ExitStatus(imp::ExitStatus);
1400 /// Allows extension traits within `std`.
1401 #[unstable(feature = "sealed", issue = "none")]
1402 impl crate::sealed::Sealed for ExitStatus {}
1405 /// Was termination successful? Returns a `Result`.
1410 /// #![feature(exit_status_error)]
1411 /// # if cfg!(unix) {
1412 /// use std::process::Command;
1414 /// let status = Command::new("ls")
1415 /// .arg("/dev/nonexistent")
1417 /// .expect("ls could not be executed");
1419 /// println!("ls: {}", status);
1420 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1421 /// # } // cfg!(unix)
1423 #[unstable(feature = "exit_status_error", issue = "84908")]
1424 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1425 self.0.exit_ok().map_err(ExitStatusError)
1428 /// Was termination successful? Signal termination is not considered a
1429 /// success, and success is defined as a zero exit status.
1434 /// use std::process::Command;
1436 /// let status = Command::new("mkdir")
1437 /// .arg("projects")
1439 /// .expect("failed to execute mkdir");
1441 /// if status.success() {
1442 /// println!("'projects/' directory created");
1444 /// println!("failed to create 'projects/' directory: {}", status);
1447 #[stable(feature = "process", since = "1.0.0")]
1448 pub fn success(&self) -> bool {
1449 self.0.exit_ok().is_ok()
1452 /// Returns the exit code of the process, if any.
1454 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1455 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1456 /// bits, and that values that didn't come from a program's call to `exit` may be invented the
1457 /// runtime system (often, for example, 255, 254, 127 or 126).
1459 /// On Unix, this will return `None` if the process was terminated by a signal.
1460 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1461 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1466 /// use std::process::Command;
1468 /// let status = Command::new("mkdir")
1469 /// .arg("projects")
1471 /// .expect("failed to execute mkdir");
1473 /// match status.code() {
1474 /// Some(code) => println!("Exited with status code: {}", code),
1475 /// None => println!("Process terminated by signal")
1478 #[stable(feature = "process", since = "1.0.0")]
1479 pub fn code(&self) -> Option<i32> {
1484 impl AsInner<imp::ExitStatus> for ExitStatus {
1485 fn as_inner(&self) -> &imp::ExitStatus {
1490 impl FromInner<imp::ExitStatus> for ExitStatus {
1491 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1496 #[stable(feature = "process", since = "1.0.0")]
1497 impl fmt::Display for ExitStatus {
1498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1503 /// Allows extension traits within `std`.
1504 #[unstable(feature = "sealed", issue = "none")]
1505 impl crate::sealed::Sealed for ExitStatusError {}
1507 /// Describes the result of a process after it has failed
1509 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1514 /// #![feature(exit_status_error)]
1515 /// # if cfg!(unix) {
1516 /// use std::process::{Command, ExitStatusError};
1518 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1519 /// Command::new(cmd).status().unwrap().exit_ok()?;
1523 /// run("true").unwrap();
1524 /// run("false").unwrap_err();
1525 /// # } // cfg!(unix)
1527 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1528 #[unstable(feature = "exit_status_error", issue = "84908")]
1529 // The definition of imp::ExitStatusError should ideally be such that
1530 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1531 pub struct ExitStatusError(imp::ExitStatusError);
1533 #[unstable(feature = "exit_status_error", issue = "84908")]
1534 impl ExitStatusError {
1535 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1537 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1538 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1539 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1540 /// runtime system (often, for example, 255, 254, 127 or 126).
1542 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1543 /// handle such situations specially, consider using methods from
1544 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1546 /// If the process finished by calling `exit` with a nonzero value, this will return
1547 /// that exit status.
1549 /// If the error was something else, it will return `None`.
1551 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1552 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1557 /// #![feature(exit_status_error)]
1558 /// # #[cfg(unix)] {
1559 /// use std::process::Command;
1561 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1562 /// assert_eq!(bad.code(), Some(1));
1563 /// # } // #[cfg(unix)]
1565 pub fn code(&self) -> Option<i32> {
1566 self.code_nonzero().map(Into::into)
1569 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1571 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1573 /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1574 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1575 /// a type-level guarantee of nonzeroness.
1580 /// #![feature(exit_status_error)]
1581 /// # if cfg!(unix) {
1582 /// use std::convert::TryFrom;
1583 /// use std::num::NonZeroI32;
1584 /// use std::process::Command;
1586 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1587 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1588 /// # } // cfg!(unix)
1590 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1594 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1595 pub fn into_status(&self) -> ExitStatus {
1596 ExitStatus(self.0.into())
1600 #[unstable(feature = "exit_status_error", issue = "84908")]
1601 impl Into<ExitStatus> for ExitStatusError {
1602 fn into(self) -> ExitStatus {
1603 ExitStatus(self.0.into())
1607 #[unstable(feature = "exit_status_error", issue = "84908")]
1608 impl fmt::Display for ExitStatusError {
1609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1610 write!(f, "process exited unsuccessfully: {}", self.into_status())
1614 #[unstable(feature = "exit_status_error", issue = "84908")]
1615 impl crate::error::Error for ExitStatusError {}
1617 /// This type represents the status code a process can return to its
1618 /// parent under normal termination.
1620 /// Numeric values used in this type don't have portable meanings, and
1621 /// different platforms may mask different amounts of them.
1623 /// For the platform's canonical successful and unsuccessful codes, see
1624 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1626 /// [`SUCCESS`]: ExitCode::SUCCESS
1627 /// [`FAILURE`]: ExitCode::FAILURE
1629 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1630 /// it was ultimately cut from that RFC, and thus this type is more subject
1631 /// to change even than the usual unstable item churn.
1633 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1634 #[derive(Clone, Copy, Debug)]
1635 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1636 pub struct ExitCode(imp::ExitCode);
1638 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1640 /// The canonical ExitCode for successful termination on this platform.
1642 /// Note that a `()`-returning `main` implicitly results in a successful
1643 /// termination, so there's no need to return this from `main` unless
1644 /// you're also returning other possible codes.
1645 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1646 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1648 /// The canonical ExitCode for unsuccessful termination on this platform.
1650 /// If you're only returning this and `SUCCESS` from `main`, consider
1651 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1652 /// return the same codes (but will also `eprintln!` the error).
1653 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1654 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1658 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1659 /// error is returned.
1661 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1663 /// This is equivalent to sending a SIGKILL on Unix platforms.
1670 /// use std::process::Command;
1672 /// let mut command = Command::new("yes");
1673 /// if let Ok(mut child) = command.spawn() {
1674 /// child.kill().expect("command wasn't running");
1676 /// println!("yes command didn't start");
1680 /// [`ErrorKind`]: io::ErrorKind
1681 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1682 #[stable(feature = "process", since = "1.0.0")]
1683 pub fn kill(&mut self) -> io::Result<()> {
1687 /// Returns the OS-assigned process identifier associated with this child.
1694 /// use std::process::Command;
1696 /// let mut command = Command::new("ls");
1697 /// if let Ok(child) = command.spawn() {
1698 /// println!("Child's ID is {}", child.id());
1700 /// println!("ls command didn't start");
1703 #[stable(feature = "process_id", since = "1.3.0")]
1704 pub fn id(&self) -> u32 {
1708 /// Waits for the child to exit completely, returning the status that it
1709 /// exited with. This function will continue to have the same return value
1710 /// after it has been called at least once.
1712 /// The stdin handle to the child process, if any, will be closed
1713 /// before waiting. This helps avoid deadlock: it ensures that the
1714 /// child does not block waiting for input from the parent, while
1715 /// the parent waits for the child to exit.
1722 /// use std::process::Command;
1724 /// let mut command = Command::new("ls");
1725 /// if let Ok(mut child) = command.spawn() {
1726 /// child.wait().expect("command wasn't running");
1727 /// println!("Child has finished its execution!");
1729 /// println!("ls command didn't start");
1732 #[stable(feature = "process", since = "1.0.0")]
1733 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1734 drop(self.stdin.take());
1735 self.handle.wait().map(ExitStatus)
1738 /// Attempts to collect the exit status of the child if it has already
1741 /// This function will not block the calling thread and will only
1742 /// check to see if the child process has exited or not. If the child has
1743 /// exited then on Unix the process ID is reaped. This function is
1744 /// guaranteed to repeatedly return a successful exit status so long as the
1745 /// child has already exited.
1747 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1748 /// exit status is not available at this time then `Ok(None)` is returned.
1749 /// If an error occurs, then that error is returned.
1751 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1758 /// use std::process::Command;
1760 /// let mut child = Command::new("ls").spawn().unwrap();
1762 /// match child.try_wait() {
1763 /// Ok(Some(status)) => println!("exited with: {}", status),
1765 /// println!("status not ready yet, let's really wait");
1766 /// let res = child.wait();
1767 /// println!("result: {:?}", res);
1769 /// Err(e) => println!("error attempting to wait: {}", e),
1772 #[stable(feature = "process_try_wait", since = "1.18.0")]
1773 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1774 Ok(self.handle.try_wait()?.map(ExitStatus))
1777 /// Simultaneously waits for the child to exit and collect all remaining
1778 /// output on the stdout/stderr handles, returning an `Output`
1781 /// The stdin handle to the child process, if any, will be closed
1782 /// before waiting. This helps avoid deadlock: it ensures that the
1783 /// child does not block waiting for input from the parent, while
1784 /// the parent waits for the child to exit.
1786 /// By default, stdin, stdout and stderr are inherited from the parent.
1787 /// In order to capture the output into this `Result<Output>` it is
1788 /// necessary to create new pipes between parent and child. Use
1789 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1794 /// use std::process::{Command, Stdio};
1796 /// let child = Command::new("/bin/cat")
1797 /// .arg("file.txt")
1798 /// .stdout(Stdio::piped())
1800 /// .expect("failed to execute child");
1802 /// let output = child
1803 /// .wait_with_output()
1804 /// .expect("failed to wait on child");
1806 /// assert!(output.status.success());
1809 #[stable(feature = "process", since = "1.0.0")]
1810 pub fn wait_with_output(mut self) -> io::Result<Output> {
1811 drop(self.stdin.take());
1813 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1814 match (self.stdout.take(), self.stderr.take()) {
1816 (Some(mut out), None) => {
1817 let res = out.read_to_end(&mut stdout);
1820 (None, Some(mut err)) => {
1821 let res = err.read_to_end(&mut stderr);
1824 (Some(out), Some(err)) => {
1825 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1830 let status = self.wait()?;
1831 Ok(Output { status, stdout, stderr })
1835 /// Terminates the current process with the specified exit code.
1837 /// This function will never return and will immediately terminate the current
1838 /// process. The exit code is passed through to the underlying OS and will be
1839 /// available for consumption by another process.
1841 /// Note that because this function never returns, and that it terminates the
1842 /// process, no destructors on the current stack or any other thread's stack
1843 /// will be run. If a clean shutdown is needed it is recommended to only call
1844 /// this function at a known point where there are no more destructors left
1847 /// ## Platform-specific behavior
1849 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1850 /// will be visible to a parent process inspecting the exit code. On most
1851 /// Unix-like platforms, only the eight least-significant bits are considered.
1855 /// Due to this function’s behavior regarding destructors, a conventional way
1856 /// to use the function is to extract the actual computation to another
1857 /// function and compute the exit code from its return value:
1860 /// fn run_app() -> Result<(), ()> {
1861 /// // Application logic here
1866 /// std::process::exit(match run_app() {
1869 /// eprintln!("error: {:?}", err);
1876 /// Due to [platform-specific behavior], the exit code for this example will be
1877 /// `0` on Linux, but `256` on Windows:
1880 /// use std::process;
1882 /// process::exit(0x0100);
1885 /// [platform-specific behavior]: #platform-specific-behavior
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 pub fn exit(code: i32) -> ! {
1888 crate::sys_common::rt::cleanup();
1889 crate::sys::os::exit(code)
1892 /// Terminates the process in an abnormal fashion.
1894 /// The function will never return and will immediately terminate the current
1895 /// process in a platform specific "abnormal" manner.
1897 /// Note that because this function never returns, and that it terminates the
1898 /// process, no destructors on the current stack or any other thread's stack
1901 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1902 /// the current thread's stack and calls all destructors.
1903 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1904 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1905 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1907 /// If a clean shutdown is needed it is recommended to only call
1908 /// this function at a known point where there are no more destructors left
1914 /// use std::process;
1917 /// println!("aborting");
1919 /// process::abort();
1921 /// // execution never gets here
1925 /// The `abort` function terminates the process, so the destructor will not
1926 /// get run on the example below:
1929 /// use std::process;
1933 /// impl Drop for HasDrop {
1934 /// fn drop(&mut self) {
1935 /// println!("This will never be printed!");
1940 /// let _x = HasDrop;
1941 /// process::abort();
1942 /// // the destructor implemented for HasDrop will never get run
1946 /// [panic hook]: crate::panic::set_hook
1947 #[stable(feature = "process_abort", since = "1.17.0")]
1949 pub fn abort() -> ! {
1950 crate::sys::abort_internal();
1953 /// Returns the OS-assigned process identifier associated with this process.
1960 /// use std::process;
1962 /// println!("My pid is {}", process::id());
1966 #[stable(feature = "getpid", since = "1.26.0")]
1967 pub fn id() -> u32 {
1968 crate::sys::os::getpid()
1971 /// A trait for implementing arbitrary return types in the `main` function.
1973 /// The C-main function only supports to return integers as return type.
1974 /// So, every type implementing the `Termination` trait has to be converted
1977 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1978 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1979 #[cfg_attr(not(test), lang = "termination")]
1980 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1981 #[rustc_on_unimplemented(
1982 message = "`main` has invalid return type `{Self}`",
1983 label = "`main` can only return types that implement `{Termination}`"
1985 pub trait Termination {
1986 /// Is called to get the representation of the value as status code.
1987 /// This status code is returned to the operating system.
1988 fn report(self) -> i32;
1991 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1992 impl Termination for () {
1994 fn report(self) -> i32 {
1995 ExitCode::SUCCESS.report()
1999 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2000 impl<E: fmt::Debug> Termination for Result<(), E> {
2001 fn report(self) -> i32 {
2003 Ok(()) => ().report(),
2004 Err(err) => Err::<!, _>(err).report(),
2009 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2010 impl Termination for ! {
2011 fn report(self) -> i32 {
2016 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2017 impl<E: fmt::Debug> Termination for Result<!, E> {
2018 fn report(self) -> i32 {
2019 let Err(err) = self;
2020 eprintln!("Error: {:?}", err);
2021 ExitCode::FAILURE.report()
2025 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2026 impl Termination for ExitCode {
2028 fn report(self) -> i32 {