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");
75 //! // limited borrow of stdin
76 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
77 //! stdin.write_all(b"test").expect("failed to write to stdin");
80 //! let output = child
81 //! .wait_with_output()
82 //! .expect("failed to wait on child");
84 //! assert_eq!(b"test", output.stdout.as_slice());
87 //! [`abort`]: fn.abort.html
88 //! [`exit`]: fn.exit.html
90 //! [`Command`]: struct.Command.html
91 //! [`spawn`]: struct.Command.html#method.spawn
92 //! [`output`]: struct.Command.html#method.output
94 //! [`Child`]: struct.Child.html
95 //! [`ChildStdin`]: struct.ChildStdin.html
96 //! [`ChildStdout`]: struct.ChildStdout.html
97 //! [`ChildStderr`]: struct.ChildStderr.html
98 //! [`Stdio`]: struct.Stdio.html
100 //! [`stdout`]: struct.Command.html#method.stdout
101 //! [`stdin`]: struct.Command.html#method.stdin
102 //! [`stderr`]: struct.Command.html#method.stderr
104 //! [`Write`]: ../io/trait.Write.html
105 //! [`Read`]: ../io/trait.Read.html
107 #![stable(feature = "process", since = "1.0.0")]
109 use crate::io::prelude::*;
111 use crate::ffi::OsStr;
114 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
115 use crate::path::Path;
117 use crate::sys::pipe::{read2, AnonPipe};
118 use crate::sys::process as imp;
119 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
121 /// Representation of a running or exited child process.
123 /// This structure is used to represent and manage child processes. A child
124 /// process is created via the [`Command`] struct, which configures the
125 /// spawning process and can itself be constructed using a builder-style
128 /// There is no implementation of [`Drop`] for child processes,
129 /// so if you do not ensure the `Child` has exited then it will continue to
130 /// run, even after the `Child` handle to the child process has gone out of
133 /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
134 /// the parent process wait until the child has actually exited before
139 /// On some system, calling [`wait`] or similar is necessary for the OS to
140 /// release resources. A process that terminated but has not been waited on is
141 /// still around as a "zombie". Leaving too many zombies around may exhaust
142 /// global resources (for example process IDs).
144 /// The standard library does *not* automatically wait on child processes (not
145 /// even if the `Child` is dropped), it is up to the application developer to do
146 /// so. As a consequence, dropping `Child` handles without waiting on them first
147 /// is not recommended in long-running applications.
152 /// use std::process::Command;
154 /// let mut child = Command::new("/bin/cat")
157 /// .expect("failed to execute child");
159 /// let ecode = child.wait()
160 /// .expect("failed to wait on child");
162 /// assert!(ecode.success());
165 /// [`Command`]: struct.Command.html
166 /// [`Drop`]: ../../core/ops/trait.Drop.html
167 /// [`wait`]: #method.wait
168 #[stable(feature = "process", since = "1.0.0")]
170 handle: imp::Process,
172 /// The handle for writing to the child's standard input (stdin), if it has
174 #[stable(feature = "process", since = "1.0.0")]
175 pub stdin: Option<ChildStdin>,
177 /// The handle for reading from the child's standard output (stdout), if it
178 /// has been captured.
179 #[stable(feature = "process", since = "1.0.0")]
180 pub stdout: Option<ChildStdout>,
182 /// The handle for reading from the child's standard error (stderr), if it
183 /// has been captured.
184 #[stable(feature = "process", since = "1.0.0")]
185 pub stderr: Option<ChildStderr>,
188 impl AsInner<imp::Process> for Child {
189 fn as_inner(&self) -> &imp::Process {
194 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
195 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
198 stdin: io.stdin.map(ChildStdin::from_inner),
199 stdout: io.stdout.map(ChildStdout::from_inner),
200 stderr: io.stderr.map(ChildStderr::from_inner),
205 impl IntoInner<imp::Process> for Child {
206 fn into_inner(self) -> imp::Process {
211 #[stable(feature = "std_debug", since = "1.16.0")]
212 impl fmt::Debug for Child {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 f.debug_struct("Child")
215 .field("stdin", &self.stdin)
216 .field("stdout", &self.stdout)
217 .field("stderr", &self.stderr)
222 /// A handle to a child process's standard input (stdin).
224 /// This struct is used in the [`stdin`] field on [`Child`].
226 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
227 /// file handle will be closed. If the child process was blocked on input prior
228 /// to being dropped, it will become unblocked after dropping.
230 /// [`Child`]: struct.Child.html
231 /// [`stdin`]: struct.Child.html#structfield.stdin
232 /// [dropped]: ../ops/trait.Drop.html
233 #[stable(feature = "process", since = "1.0.0")]
234 pub struct ChildStdin {
238 #[stable(feature = "process", since = "1.0.0")]
239 impl Write for ChildStdin {
240 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
241 self.inner.write(buf)
244 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
245 self.inner.write_vectored(bufs)
248 fn flush(&mut self) -> io::Result<()> {
253 impl AsInner<AnonPipe> for ChildStdin {
254 fn as_inner(&self) -> &AnonPipe {
259 impl IntoInner<AnonPipe> for ChildStdin {
260 fn into_inner(self) -> AnonPipe {
265 impl FromInner<AnonPipe> for ChildStdin {
266 fn from_inner(pipe: AnonPipe) -> ChildStdin {
267 ChildStdin { inner: pipe }
271 #[stable(feature = "std_debug", since = "1.16.0")]
272 impl fmt::Debug for ChildStdin {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 f.pad("ChildStdin { .. }")
278 /// A handle to a child process's standard output (stdout).
280 /// This struct is used in the [`stdout`] field on [`Child`].
282 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
283 /// underlying file handle will be closed.
285 /// [`Child`]: struct.Child.html
286 /// [`stdout`]: struct.Child.html#structfield.stdout
287 /// [dropped]: ../ops/trait.Drop.html
288 #[stable(feature = "process", since = "1.0.0")]
289 pub struct ChildStdout {
293 #[stable(feature = "process", since = "1.0.0")]
294 impl Read for ChildStdout {
295 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
299 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
300 self.inner.read_vectored(bufs)
304 unsafe fn initializer(&self) -> Initializer {
309 impl AsInner<AnonPipe> for ChildStdout {
310 fn as_inner(&self) -> &AnonPipe {
315 impl IntoInner<AnonPipe> for ChildStdout {
316 fn into_inner(self) -> AnonPipe {
321 impl FromInner<AnonPipe> for ChildStdout {
322 fn from_inner(pipe: AnonPipe) -> ChildStdout {
323 ChildStdout { inner: pipe }
327 #[stable(feature = "std_debug", since = "1.16.0")]
328 impl fmt::Debug for ChildStdout {
329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330 f.pad("ChildStdout { .. }")
334 /// A handle to a child process's stderr.
336 /// This struct is used in the [`stderr`] field on [`Child`].
338 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
339 /// underlying file handle will be closed.
341 /// [`Child`]: struct.Child.html
342 /// [`stderr`]: struct.Child.html#structfield.stderr
343 /// [dropped]: ../ops/trait.Drop.html
344 #[stable(feature = "process", since = "1.0.0")]
345 pub struct ChildStderr {
349 #[stable(feature = "process", since = "1.0.0")]
350 impl Read for ChildStderr {
351 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
355 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
356 self.inner.read_vectored(bufs)
360 unsafe fn initializer(&self) -> Initializer {
365 impl AsInner<AnonPipe> for ChildStderr {
366 fn as_inner(&self) -> &AnonPipe {
371 impl IntoInner<AnonPipe> for ChildStderr {
372 fn into_inner(self) -> AnonPipe {
377 impl FromInner<AnonPipe> for ChildStderr {
378 fn from_inner(pipe: AnonPipe) -> ChildStderr {
379 ChildStderr { inner: pipe }
383 #[stable(feature = "std_debug", since = "1.16.0")]
384 impl fmt::Debug for ChildStderr {
385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386 f.pad("ChildStderr { .. }")
390 /// A process builder, providing fine-grained control
391 /// over how a new process should be spawned.
393 /// A default configuration can be
394 /// generated using `Command::new(program)`, where `program` gives a path to the
395 /// program to be executed. Additional builder methods allow the configuration
396 /// to be changed (for example, by adding arguments) prior to spawning:
399 /// use std::process::Command;
401 /// let output = if cfg!(target_os = "windows") {
402 /// Command::new("cmd")
403 /// .args(&["/C", "echo hello"])
405 /// .expect("failed to execute process")
407 /// Command::new("sh")
409 /// .arg("echo hello")
411 /// .expect("failed to execute process")
414 /// let hello = output.stdout;
417 /// `Command` can be reused to spawn multiple processes. The builder methods
418 /// change the command without needing to immediately spawn the process.
421 /// use std::process::Command;
423 /// let mut echo_hello = Command::new("sh");
424 /// echo_hello.arg("-c")
425 /// .arg("echo hello");
426 /// let hello_1 = echo_hello.output().expect("failed to execute process");
427 /// let hello_2 = echo_hello.output().expect("failed to execute process");
430 /// Similarly, you can call builder methods after spawning a process and then
431 /// spawn a new process with the modified settings.
434 /// use std::process::Command;
436 /// let mut list_dir = Command::new("ls");
438 /// // Execute `ls` in the current directory of the program.
439 /// list_dir.status().expect("process failed to execute");
443 /// // Change `ls` to execute in the root directory.
444 /// list_dir.current_dir("/");
446 /// // And then execute `ls` again but in the root directory.
447 /// list_dir.status().expect("process failed to execute");
449 #[stable(feature = "process", since = "1.0.0")]
455 /// Constructs a new `Command` for launching the program at
456 /// path `program`, with the following default configuration:
458 /// * No arguments to the program
459 /// * Inherit the current process's environment
460 /// * Inherit the current process's working directory
461 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
463 /// Builder methods are provided to change these defaults and
464 /// otherwise configure the process.
466 /// If `program` is not an absolute path, the `PATH` will be searched in
467 /// an OS-defined way.
469 /// The search path to be used may be controlled by setting the
470 /// `PATH` environment variable on the Command,
471 /// but this has some implementation limitations on Windows
472 /// (see issue #37519).
479 /// use std::process::Command;
481 /// Command::new("sh")
483 /// .expect("sh command failed to start");
485 #[stable(feature = "process", since = "1.0.0")]
486 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
487 Command { inner: imp::Command::new(program.as_ref()) }
490 /// Adds an argument to pass to the program.
492 /// Only one argument can be passed per use. So instead of:
495 /// # std::process::Command::new("sh")
496 /// .arg("-C /path/to/repo")
503 /// # std::process::Command::new("sh")
505 /// .arg("/path/to/repo")
509 /// To pass multiple arguments see [`args`].
511 /// [`args`]: #method.args
518 /// use std::process::Command;
520 /// Command::new("ls")
524 /// .expect("ls command failed to start");
526 #[stable(feature = "process", since = "1.0.0")]
527 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
528 self.inner.arg(arg.as_ref());
532 /// Adds multiple arguments to pass to the program.
534 /// To pass a single argument see [`arg`].
536 /// [`arg`]: #method.arg
543 /// use std::process::Command;
545 /// Command::new("ls")
546 /// .args(&["-l", "-a"])
548 /// .expect("ls command failed to start");
550 #[stable(feature = "process", since = "1.0.0")]
551 pub fn args<I, S>(&mut self, args: I) -> &mut Command
553 I: IntoIterator<Item = S>,
557 self.arg(arg.as_ref());
562 /// Inserts or updates an environment variable mapping.
564 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
565 /// and case-sensitive on all other platforms.
572 /// use std::process::Command;
574 /// Command::new("ls")
575 /// .env("PATH", "/bin")
577 /// .expect("ls command failed to start");
579 #[stable(feature = "process", since = "1.0.0")]
580 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
585 self.inner.env_mut().set(key.as_ref(), val.as_ref());
589 /// Adds or updates multiple environment variable mappings.
596 /// use std::process::{Command, Stdio};
598 /// use std::collections::HashMap;
600 /// let filtered_env : HashMap<String, String> =
601 /// env::vars().filter(|&(ref k, _)|
602 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
605 /// Command::new("printenv")
606 /// .stdin(Stdio::null())
607 /// .stdout(Stdio::inherit())
609 /// .envs(&filtered_env)
611 /// .expect("printenv failed to start");
613 #[stable(feature = "command_envs", since = "1.19.0")]
614 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
616 I: IntoIterator<Item = (K, V)>,
620 for (ref key, ref val) in vars {
621 self.inner.env_mut().set(key.as_ref(), val.as_ref());
626 /// Removes an environment variable mapping.
633 /// use std::process::Command;
635 /// Command::new("ls")
636 /// .env_remove("PATH")
638 /// .expect("ls command failed to start");
640 #[stable(feature = "process", since = "1.0.0")]
641 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
642 self.inner.env_mut().remove(key.as_ref());
646 /// Clears the entire environment map for the child process.
653 /// use std::process::Command;
655 /// Command::new("ls")
658 /// .expect("ls command failed to start");
660 #[stable(feature = "process", since = "1.0.0")]
661 pub fn env_clear(&mut self) -> &mut Command {
662 self.inner.env_mut().clear();
666 /// Sets the working directory for the child process.
668 /// # Platform-specific behavior
670 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
671 /// whether it should be interpreted relative to the parent's working
672 /// directory or relative to `current_dir`. The behavior in this case is
673 /// platform specific and unstable, and it's recommended to use
674 /// [`canonicalize`] to get an absolute program path instead.
681 /// use std::process::Command;
683 /// Command::new("ls")
684 /// .current_dir("/bin")
686 /// .expect("ls command failed to start");
689 /// [`canonicalize`]: ../fs/fn.canonicalize.html
690 #[stable(feature = "process", since = "1.0.0")]
691 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
692 self.inner.cwd(dir.as_ref().as_ref());
696 /// Configuration for the child process's standard input (stdin) handle.
698 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
699 /// defaults to [`piped`] when used with `output`.
701 /// [`inherit`]: struct.Stdio.html#method.inherit
702 /// [`piped`]: struct.Stdio.html#method.piped
709 /// use std::process::{Command, Stdio};
711 /// Command::new("ls")
712 /// .stdin(Stdio::null())
714 /// .expect("ls command failed to start");
716 #[stable(feature = "process", since = "1.0.0")]
717 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
718 self.inner.stdin(cfg.into().0);
722 /// Configuration for the child process's standard output (stdout) handle.
724 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
725 /// defaults to [`piped`] when used with `output`.
727 /// [`inherit`]: struct.Stdio.html#method.inherit
728 /// [`piped`]: struct.Stdio.html#method.piped
735 /// use std::process::{Command, Stdio};
737 /// Command::new("ls")
738 /// .stdout(Stdio::null())
740 /// .expect("ls command failed to start");
742 #[stable(feature = "process", since = "1.0.0")]
743 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
744 self.inner.stdout(cfg.into().0);
748 /// Configuration for the child process's standard error (stderr) handle.
750 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
751 /// defaults to [`piped`] when used with `output`.
753 /// [`inherit`]: struct.Stdio.html#method.inherit
754 /// [`piped`]: struct.Stdio.html#method.piped
761 /// use std::process::{Command, Stdio};
763 /// Command::new("ls")
764 /// .stderr(Stdio::null())
766 /// .expect("ls command failed to start");
768 #[stable(feature = "process", since = "1.0.0")]
769 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
770 self.inner.stderr(cfg.into().0);
774 /// Executes the command as a child process, returning a handle to it.
776 /// By default, stdin, stdout and stderr are inherited from the parent.
783 /// use std::process::Command;
785 /// Command::new("ls")
787 /// .expect("ls command failed to start");
789 #[stable(feature = "process", since = "1.0.0")]
790 pub fn spawn(&mut self) -> io::Result<Child> {
791 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
794 /// Executes the command as a child process, waiting for it to finish and
795 /// collecting all of its output.
797 /// By default, stdout and stderr are captured (and used to provide the
798 /// resulting output). Stdin is not inherited from the parent and any
799 /// attempt by the child process to read from the stdin stream will result
800 /// in the stream immediately closing.
805 /// use std::process::Command;
806 /// use std::io::{self, Write};
807 /// let output = Command::new("/bin/cat")
810 /// .expect("failed to execute process");
812 /// println!("status: {}", output.status);
813 /// io::stdout().write_all(&output.stdout).unwrap();
814 /// io::stderr().write_all(&output.stderr).unwrap();
816 /// assert!(output.status.success());
818 #[stable(feature = "process", since = "1.0.0")]
819 pub fn output(&mut self) -> io::Result<Output> {
821 .spawn(imp::Stdio::MakePipe, false)
822 .map(Child::from_inner)
823 .and_then(|p| p.wait_with_output())
826 /// Executes a command as a child process, waiting for it to finish and
827 /// collecting its exit status.
829 /// By default, stdin, stdout and stderr are inherited from the parent.
834 /// use std::process::Command;
836 /// let status = Command::new("/bin/cat")
839 /// .expect("failed to execute process");
841 /// println!("process exited with: {}", status);
843 /// assert!(status.success());
845 #[stable(feature = "process", since = "1.0.0")]
846 pub fn status(&mut self) -> io::Result<ExitStatus> {
848 .spawn(imp::Stdio::Inherit, true)
849 .map(Child::from_inner)
850 .and_then(|mut p| p.wait())
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl fmt::Debug for Command {
856 /// Format the program and arguments of a Command for display. Any
857 /// non-utf8 data is lossily converted using the utf8 replacement
859 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864 impl AsInner<imp::Command> for Command {
865 fn as_inner(&self) -> &imp::Command {
870 impl AsInnerMut<imp::Command> for Command {
871 fn as_inner_mut(&mut self) -> &mut imp::Command {
876 /// The output of a finished process.
878 /// This is returned in a Result by either the [`output`] method of a
879 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
882 /// [`Command`]: struct.Command.html
883 /// [`Child`]: struct.Child.html
884 /// [`output`]: struct.Command.html#method.output
885 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
886 #[derive(PartialEq, Eq, Clone)]
887 #[stable(feature = "process", since = "1.0.0")]
889 /// The status (exit code) of the process.
890 #[stable(feature = "process", since = "1.0.0")]
891 pub status: ExitStatus,
892 /// The data that the process wrote to stdout.
893 #[stable(feature = "process", since = "1.0.0")]
895 /// The data that the process wrote to stderr.
896 #[stable(feature = "process", since = "1.0.0")]
900 // If either stderr or stdout are valid utf8 strings it prints the valid
901 // strings, otherwise it prints the byte sequence instead
902 #[stable(feature = "process_output_debug", since = "1.7.0")]
903 impl fmt::Debug for Output {
904 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
905 let stdout_utf8 = str::from_utf8(&self.stdout);
906 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
908 Err(_) => &self.stdout,
911 let stderr_utf8 = str::from_utf8(&self.stderr);
912 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
914 Err(_) => &self.stderr,
917 fmt.debug_struct("Output")
918 .field("status", &self.status)
919 .field("stdout", stdout_debug)
920 .field("stderr", stderr_debug)
925 /// Describes what to do with a standard I/O stream for a child process when
926 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
928 /// [`stdin`]: struct.Command.html#method.stdin
929 /// [`stdout`]: struct.Command.html#method.stdout
930 /// [`stderr`]: struct.Command.html#method.stderr
931 /// [`Command`]: struct.Command.html
932 #[stable(feature = "process", since = "1.0.0")]
933 pub struct Stdio(imp::Stdio);
936 /// A new pipe should be arranged to connect the parent and child processes.
943 /// use std::process::{Command, Stdio};
945 /// let output = Command::new("echo")
946 /// .arg("Hello, world!")
947 /// .stdout(Stdio::piped())
949 /// .expect("Failed to execute command");
951 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
952 /// // Nothing echoed to console
958 /// use std::io::Write;
959 /// use std::process::{Command, Stdio};
961 /// let mut child = Command::new("rev")
962 /// .stdin(Stdio::piped())
963 /// .stdout(Stdio::piped())
965 /// .expect("Failed to spawn child process");
968 /// let stdin = child.stdin.as_mut().expect("Failed to open stdin");
969 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
972 /// let output = child.wait_with_output().expect("Failed to read stdout");
973 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
975 #[stable(feature = "process", since = "1.0.0")]
976 pub fn piped() -> Stdio {
977 Stdio(imp::Stdio::MakePipe)
980 /// The child inherits from the corresponding parent descriptor.
987 /// use std::process::{Command, Stdio};
989 /// let output = Command::new("echo")
990 /// .arg("Hello, world!")
991 /// .stdout(Stdio::inherit())
993 /// .expect("Failed to execute command");
995 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
996 /// // "Hello, world!" echoed to console
1002 /// use std::process::{Command, Stdio};
1003 /// use std::io::{self, Write};
1005 /// let output = Command::new("rev")
1006 /// .stdin(Stdio::inherit())
1007 /// .stdout(Stdio::piped())
1009 /// .expect("Failed to execute command");
1011 /// print!("You piped in the reverse of: ");
1012 /// io::stdout().write_all(&output.stdout).unwrap();
1014 #[stable(feature = "process", since = "1.0.0")]
1015 pub fn inherit() -> Stdio {
1016 Stdio(imp::Stdio::Inherit)
1019 /// This stream will be ignored. This is the equivalent of attaching the
1020 /// stream to `/dev/null`
1027 /// use std::process::{Command, Stdio};
1029 /// let output = Command::new("echo")
1030 /// .arg("Hello, world!")
1031 /// .stdout(Stdio::null())
1033 /// .expect("Failed to execute command");
1035 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1036 /// // Nothing echoed to console
1042 /// use std::process::{Command, Stdio};
1044 /// let output = Command::new("rev")
1045 /// .stdin(Stdio::null())
1046 /// .stdout(Stdio::piped())
1048 /// .expect("Failed to execute command");
1050 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1051 /// // Ignores any piped-in input
1053 #[stable(feature = "process", since = "1.0.0")]
1054 pub fn null() -> Stdio {
1055 Stdio(imp::Stdio::Null)
1059 impl FromInner<imp::Stdio> for Stdio {
1060 fn from_inner(inner: imp::Stdio) -> Stdio {
1065 #[stable(feature = "std_debug", since = "1.16.0")]
1066 impl fmt::Debug for Stdio {
1067 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1068 f.pad("Stdio { .. }")
1072 #[stable(feature = "stdio_from", since = "1.20.0")]
1073 impl From<ChildStdin> for Stdio {
1074 /// Converts a `ChildStdin` into a `Stdio`
1078 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1081 /// use std::process::{Command, Stdio};
1083 /// let reverse = Command::new("rev")
1084 /// .stdin(Stdio::piped())
1086 /// .expect("failed reverse command");
1088 /// let _echo = Command::new("echo")
1089 /// .arg("Hello, world!")
1090 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1092 /// .expect("failed echo command");
1094 /// // "!dlrow ,olleH" echoed to console
1096 fn from(child: ChildStdin) -> Stdio {
1097 Stdio::from_inner(child.into_inner().into())
1101 #[stable(feature = "stdio_from", since = "1.20.0")]
1102 impl From<ChildStdout> for Stdio {
1103 /// Converts a `ChildStdout` into a `Stdio`
1107 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1110 /// use std::process::{Command, Stdio};
1112 /// let hello = Command::new("echo")
1113 /// .arg("Hello, world!")
1114 /// .stdout(Stdio::piped())
1116 /// .expect("failed echo command");
1118 /// let reverse = Command::new("rev")
1119 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1121 /// .expect("failed reverse command");
1123 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1125 fn from(child: ChildStdout) -> Stdio {
1126 Stdio::from_inner(child.into_inner().into())
1130 #[stable(feature = "stdio_from", since = "1.20.0")]
1131 impl From<ChildStderr> for Stdio {
1132 /// Converts a `ChildStderr` into a `Stdio`
1137 /// use std::process::{Command, Stdio};
1139 /// let reverse = Command::new("rev")
1140 /// .arg("non_existing_file.txt")
1141 /// .stderr(Stdio::piped())
1143 /// .expect("failed reverse command");
1145 /// let cat = Command::new("cat")
1147 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1149 /// .expect("failed echo command");
1152 /// String::from_utf8_lossy(&cat.stdout),
1153 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1156 fn from(child: ChildStderr) -> Stdio {
1157 Stdio::from_inner(child.into_inner().into())
1161 #[stable(feature = "stdio_from", since = "1.20.0")]
1162 impl From<fs::File> for Stdio {
1163 /// Converts a `File` into a `Stdio`
1167 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1170 /// use std::fs::File;
1171 /// use std::process::Command;
1173 /// // With the `foo.txt` file containing `Hello, world!"
1174 /// let file = File::open("foo.txt").unwrap();
1176 /// let reverse = Command::new("rev")
1177 /// .stdin(file) // Implicit File conversion into a Stdio
1179 /// .expect("failed reverse command");
1181 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1183 fn from(file: fs::File) -> Stdio {
1184 Stdio::from_inner(file.into_inner().into())
1188 /// Describes the result of a process after it has terminated.
1190 /// This `struct` is used to represent the exit status of a child process.
1191 /// Child processes are created via the [`Command`] struct and their exit
1192 /// status is exposed through the [`status`] method, or the [`wait`] method
1193 /// of a [`Child`] process.
1195 /// [`Command`]: struct.Command.html
1196 /// [`Child`]: struct.Child.html
1197 /// [`status`]: struct.Command.html#method.status
1198 /// [`wait`]: struct.Child.html#method.wait
1199 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1200 #[stable(feature = "process", since = "1.0.0")]
1201 pub struct ExitStatus(imp::ExitStatus);
1204 /// Was termination successful? Signal termination is not considered a
1205 /// success, and success is defined as a zero exit status.
1210 /// use std::process::Command;
1212 /// let status = Command::new("mkdir")
1213 /// .arg("projects")
1215 /// .expect("failed to execute mkdir");
1217 /// if status.success() {
1218 /// println!("'projects/' directory created");
1220 /// println!("failed to create 'projects/' directory");
1223 #[stable(feature = "process", since = "1.0.0")]
1224 pub fn success(&self) -> bool {
1228 /// Returns the exit code of the process, if any.
1230 /// On Unix, this will return `None` if the process was terminated
1231 /// by a signal; `std::os::unix` provides an extension trait for
1232 /// extracting the signal and other details from the `ExitStatus`.
1237 /// use std::process::Command;
1239 /// let status = Command::new("mkdir")
1240 /// .arg("projects")
1242 /// .expect("failed to execute mkdir");
1244 /// match status.code() {
1245 /// Some(code) => println!("Exited with status code: {}", code),
1246 /// None => println!("Process terminated by signal")
1249 #[stable(feature = "process", since = "1.0.0")]
1250 pub fn code(&self) -> Option<i32> {
1255 impl AsInner<imp::ExitStatus> for ExitStatus {
1256 fn as_inner(&self) -> &imp::ExitStatus {
1261 impl FromInner<imp::ExitStatus> for ExitStatus {
1262 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1267 #[stable(feature = "process", since = "1.0.0")]
1268 impl fmt::Display for ExitStatus {
1269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1274 /// This type represents the status code a process can return to its
1275 /// parent under normal termination.
1277 /// Numeric values used in this type don't have portable meanings, and
1278 /// different platforms may mask different amounts of them.
1280 /// For the platform's canonical successful and unsuccessful codes, see
1281 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1283 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1284 /// [`FAILURE`]: #associatedconstant.FAILURE
1286 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1287 /// it was ultimately cut from that RFC, and thus this type is more subject
1288 /// to change even than the usual unstable item churn.
1290 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1291 #[derive(Clone, Copy, Debug)]
1292 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1293 pub struct ExitCode(imp::ExitCode);
1295 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1297 /// The canonical ExitCode for successful termination on this platform.
1299 /// Note that a `()`-returning `main` implicitly results in a successful
1300 /// termination, so there's no need to return this from `main` unless
1301 /// you're also returning other possible codes.
1302 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1303 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1305 /// The canonical ExitCode for unsuccessful termination on this platform.
1307 /// If you're only returning this and `SUCCESS` from `main`, consider
1308 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1309 /// return the same codes (but will also `eprintln!` the error).
1310 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1311 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1315 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1316 /// error is returned.
1318 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1319 /// especially the [`Other`] kind might change to more specific kinds in the future.
1321 /// This is equivalent to sending a SIGKILL on Unix platforms.
1328 /// use std::process::Command;
1330 /// let mut command = Command::new("yes");
1331 /// if let Ok(mut child) = command.spawn() {
1332 /// child.kill().expect("command wasn't running");
1334 /// println!("yes command didn't start");
1338 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1339 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1340 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1341 #[stable(feature = "process", since = "1.0.0")]
1342 pub fn kill(&mut self) -> io::Result<()> {
1346 /// Returns the OS-assigned process identifier associated with this child.
1353 /// use std::process::Command;
1355 /// let mut command = Command::new("ls");
1356 /// if let Ok(child) = command.spawn() {
1357 /// println!("Child's ID is {}", child.id());
1359 /// println!("ls command didn't start");
1362 #[stable(feature = "process_id", since = "1.3.0")]
1363 pub fn id(&self) -> u32 {
1367 /// Waits for the child to exit completely, returning the status that it
1368 /// exited with. This function will continue to have the same return value
1369 /// after it has been called at least once.
1371 /// The stdin handle to the child process, if any, will be closed
1372 /// before waiting. This helps avoid deadlock: it ensures that the
1373 /// child does not block waiting for input from the parent, while
1374 /// the parent waits for the child to exit.
1381 /// use std::process::Command;
1383 /// let mut command = Command::new("ls");
1384 /// if let Ok(mut child) = command.spawn() {
1385 /// child.wait().expect("command wasn't running");
1386 /// println!("Child has finished its execution!");
1388 /// println!("ls command didn't start");
1391 #[stable(feature = "process", since = "1.0.0")]
1392 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1393 drop(self.stdin.take());
1394 self.handle.wait().map(ExitStatus)
1397 /// Attempts to collect the exit status of the child if it has already
1400 /// This function will not block the calling thread and will only
1401 /// check to see if the child process has exited or not. If the child has
1402 /// exited then on Unix the process ID is reaped. This function is
1403 /// guaranteed to repeatedly return a successful exit status so long as the
1404 /// child has already exited.
1406 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1407 /// exit status is not available at this time then `Ok(None)` is returned.
1408 /// If an error occurs, then that error is returned.
1410 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1417 /// use std::process::Command;
1419 /// let mut child = Command::new("ls").spawn().unwrap();
1421 /// match child.try_wait() {
1422 /// Ok(Some(status)) => println!("exited with: {}", status),
1424 /// println!("status not ready yet, let's really wait");
1425 /// let res = child.wait();
1426 /// println!("result: {:?}", res);
1428 /// Err(e) => println!("error attempting to wait: {}", e),
1431 #[stable(feature = "process_try_wait", since = "1.18.0")]
1432 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1433 Ok(self.handle.try_wait()?.map(ExitStatus))
1436 /// Simultaneously waits for the child to exit and collect all remaining
1437 /// output on the stdout/stderr handles, returning an `Output`
1440 /// The stdin handle to the child process, if any, will be closed
1441 /// before waiting. This helps avoid deadlock: it ensures that the
1442 /// child does not block waiting for input from the parent, while
1443 /// the parent waits for the child to exit.
1445 /// By default, stdin, stdout and stderr are inherited from the parent.
1446 /// In order to capture the output into this `Result<Output>` it is
1447 /// necessary to create new pipes between parent and child. Use
1448 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1453 /// use std::process::{Command, Stdio};
1455 /// let child = Command::new("/bin/cat")
1456 /// .arg("file.txt")
1457 /// .stdout(Stdio::piped())
1459 /// .expect("failed to execute child");
1461 /// let output = child
1462 /// .wait_with_output()
1463 /// .expect("failed to wait on child");
1465 /// assert!(output.status.success());
1468 #[stable(feature = "process", since = "1.0.0")]
1469 pub fn wait_with_output(mut self) -> io::Result<Output> {
1470 drop(self.stdin.take());
1472 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1473 match (self.stdout.take(), self.stderr.take()) {
1475 (Some(mut out), None) => {
1476 let res = out.read_to_end(&mut stdout);
1479 (None, Some(mut err)) => {
1480 let res = err.read_to_end(&mut stderr);
1483 (Some(out), Some(err)) => {
1484 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1489 let status = self.wait()?;
1490 Ok(Output { status, stdout, stderr })
1494 /// Terminates the current process with the specified exit code.
1496 /// This function will never return and will immediately terminate the current
1497 /// process. The exit code is passed through to the underlying OS and will be
1498 /// available for consumption by another process.
1500 /// Note that because this function never returns, and that it terminates the
1501 /// process, no destructors on the current stack or any other thread's stack
1502 /// will be run. If a clean shutdown is needed it is recommended to only call
1503 /// this function at a known point where there are no more destructors left
1506 /// ## Platform-specific behavior
1508 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1509 /// will be visible to a parent process inspecting the exit code. On most
1510 /// Unix-like platforms, only the eight least-significant bits are considered.
1514 /// Due to this function’s behavior regarding destructors, a conventional way
1515 /// to use the function is to extract the actual computation to another
1516 /// function and compute the exit code from its return value:
1519 /// fn run_app() -> Result<(), ()> {
1520 /// // Application logic here
1525 /// std::process::exit(match run_app() {
1528 /// eprintln!("error: {:?}", err);
1535 /// Due to [platform-specific behavior], the exit code for this example will be
1536 /// `0` on Linux, but `256` on Windows:
1539 /// use std::process;
1541 /// process::exit(0x0100);
1544 /// [platform-specific behavior]: #platform-specific-behavior
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 pub fn exit(code: i32) -> ! {
1547 crate::sys_common::cleanup();
1548 crate::sys::os::exit(code)
1551 /// Terminates the process in an abnormal fashion.
1553 /// The function will never return and will immediately terminate the current
1554 /// process in a platform specific "abnormal" manner.
1556 /// Note that because this function never returns, and that it terminates the
1557 /// process, no destructors on the current stack or any other thread's stack
1560 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1561 /// the current thread's stack and calls all destructors.
1562 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1563 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1564 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1566 /// If a clean shutdown is needed it is recommended to only call
1567 /// this function at a known point where there are no more destructors left
1573 /// use std::process;
1576 /// println!("aborting");
1578 /// process::abort();
1580 /// // execution never gets here
1584 /// The `abort` function terminates the process, so the destructor will not
1585 /// get run on the example below:
1588 /// use std::process;
1592 /// impl Drop for HasDrop {
1593 /// fn drop(&mut self) {
1594 /// println!("This will never be printed!");
1599 /// let _x = HasDrop;
1600 /// process::abort();
1601 /// // the destructor implemented for HasDrop will never get run
1605 /// [`panic!`]: ../../std/macro.panic.html
1606 /// [panic hook]: ../../std/panic/fn.set_hook.html
1607 #[stable(feature = "process_abort", since = "1.17.0")]
1608 pub fn abort() -> ! {
1609 unsafe { crate::sys::abort_internal() };
1612 /// Returns the OS-assigned process identifier associated with this process.
1619 /// use std::process;
1621 /// println!("My pid is {}", process::id());
1625 #[stable(feature = "getpid", since = "1.26.0")]
1626 pub fn id() -> u32 {
1627 crate::sys::os::getpid()
1630 /// A trait for implementing arbitrary return types in the `main` function.
1632 /// The C-main function only supports to return integers as return type.
1633 /// So, every type implementing the `Termination` trait has to be converted
1636 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1637 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1638 #[cfg_attr(not(test), lang = "termination")]
1639 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1640 #[rustc_on_unimplemented(
1641 message = "`main` has invalid return type `{Self}`",
1642 label = "`main` can only return types that implement `{Termination}`"
1644 pub trait Termination {
1645 /// Is called to get the representation of the value as status code.
1646 /// This status code is returned to the operating system.
1647 fn report(self) -> i32;
1650 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1651 impl Termination for () {
1653 fn report(self) -> i32 {
1654 ExitCode::SUCCESS.report()
1658 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1659 impl<E: fmt::Debug> Termination for Result<(), E> {
1660 fn report(self) -> i32 {
1662 Ok(()) => ().report(),
1663 Err(err) => Err::<!, _>(err).report(),
1668 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1669 impl Termination for ! {
1670 fn report(self) -> i32 {
1675 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1676 impl<E: fmt::Debug> Termination for Result<!, E> {
1677 fn report(self) -> i32 {
1678 let Err(err) = self;
1679 eprintln!("Error: {:?}", err);
1680 ExitCode::FAILURE.report()
1684 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1685 impl Termination for ExitCode {
1687 fn report(self) -> i32 {
1692 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
1694 use crate::io::prelude::*;
1696 use super::{Command, Output, Stdio};
1697 use crate::io::ErrorKind;
1700 // FIXME(#10380) these tests should not all be ignored on android.
1703 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1705 let p = if cfg!(target_os = "windows") {
1706 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1708 Command::new("true").spawn()
1711 let mut p = p.unwrap();
1712 assert!(p.wait().unwrap().success());
1716 #[cfg_attr(target_os = "android", ignore)]
1717 fn smoke_failure() {
1718 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1725 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1726 fn exit_reported_right() {
1727 let p = if cfg!(target_os = "windows") {
1728 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1730 Command::new("false").spawn()
1733 let mut p = p.unwrap();
1734 assert!(p.wait().unwrap().code() == Some(1));
1740 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1741 fn signal_reported_right() {
1742 use crate::os::unix::process::ExitStatusExt;
1745 Command::new("/bin/sh").arg("-c").arg("read a").stdin(Stdio::piped()).spawn().unwrap();
1747 match p.wait().unwrap().signal() {
1749 result => panic!("not terminated by signal 9 (instead, {:?})", result),
1753 pub fn run_output(mut cmd: Command) -> String {
1754 let p = cmd.spawn();
1756 let mut p = p.unwrap();
1757 assert!(p.stdout.is_some());
1758 let mut ret = String::new();
1759 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1760 assert!(p.wait().unwrap().success());
1765 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1767 if cfg!(target_os = "windows") {
1768 let mut cmd = Command::new("cmd");
1769 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1770 assert_eq!(run_output(cmd), "foobar\r\n");
1772 let mut cmd = Command::new("echo");
1773 cmd.arg("foobar").stdout(Stdio::piped());
1774 assert_eq!(run_output(cmd), "foobar\n");
1779 #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
1780 fn set_current_dir_works() {
1781 let mut cmd = Command::new("/bin/sh");
1782 cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped());
1783 assert_eq!(run_output(cmd), "/\n");
1787 #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
1789 let mut p = Command::new("/bin/sh")
1791 .arg("read line; echo $line")
1792 .stdin(Stdio::piped())
1793 .stdout(Stdio::piped())
1796 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1797 drop(p.stdin.take());
1798 let mut out = String::new();
1799 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1800 assert!(p.wait().unwrap().success());
1801 assert_eq!(out, "foobar\n");
1805 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1806 fn test_process_status() {
1807 let mut status = if cfg!(target_os = "windows") {
1808 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1810 Command::new("false").status().unwrap()
1812 assert!(status.code() == Some(1));
1814 status = if cfg!(target_os = "windows") {
1815 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1817 Command::new("true").status().unwrap()
1819 assert!(status.success());
1823 fn test_process_output_fail_to_start() {
1824 match Command::new("/no-binary-by-this-name-should-exist").output() {
1825 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1831 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1832 fn test_process_output_output() {
1833 let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
1834 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1836 Command::new("echo").arg("hello").output().unwrap()
1838 let output_str = str::from_utf8(&stdout).unwrap();
1840 assert!(status.success());
1841 assert_eq!(output_str.trim().to_string(), "hello");
1842 assert_eq!(stderr, Vec::new());
1846 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1847 fn test_process_output_error() {
1848 let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
1849 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1851 Command::new("mkdir").arg("./").output().unwrap()
1854 assert!(status.code() == Some(1));
1855 assert_eq!(stdout, Vec::new());
1856 assert!(!stderr.is_empty());
1860 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1861 fn test_finish_once() {
1862 let mut prog = if cfg!(target_os = "windows") {
1863 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1865 Command::new("false").spawn().unwrap()
1867 assert!(prog.wait().unwrap().code() == Some(1));
1871 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1872 fn test_finish_twice() {
1873 let mut prog = if cfg!(target_os = "windows") {
1874 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1876 Command::new("false").spawn().unwrap()
1878 assert!(prog.wait().unwrap().code() == Some(1));
1879 assert!(prog.wait().unwrap().code() == Some(1));
1883 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1884 fn test_wait_with_output_once() {
1885 let prog = if cfg!(target_os = "windows") {
1886 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1888 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1891 let Output { status, stdout, stderr } = prog.wait_with_output().unwrap();
1892 let output_str = str::from_utf8(&stdout).unwrap();
1894 assert!(status.success());
1895 assert_eq!(output_str.trim().to_string(), "hello");
1896 assert_eq!(stderr, Vec::new());
1899 #[cfg(all(unix, not(target_os = "android")))]
1900 pub fn env_cmd() -> Command {
1903 #[cfg(target_os = "android")]
1904 pub fn env_cmd() -> Command {
1905 let mut cmd = Command::new("/system/bin/sh");
1906 cmd.arg("-c").arg("set");
1911 pub fn env_cmd() -> Command {
1912 let mut cmd = Command::new("cmd");
1913 cmd.arg("/c").arg("set");
1918 #[cfg_attr(target_os = "vxworks", ignore)]
1919 fn test_override_env() {
1922 // In some build environments (such as chrooted Nix builds), `env` can
1923 // only be found in the explicitly-provided PATH env variable, not in
1924 // default places such as /bin or /usr/bin. So we need to pass through
1925 // PATH to our sub-process.
1926 let mut cmd = env_cmd();
1927 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1928 if let Some(p) = env::var_os("PATH") {
1929 cmd.env("PATH", &p);
1931 let result = cmd.output().unwrap();
1932 let output = String::from_utf8_lossy(&result.stdout).to_string();
1935 output.contains("RUN_TEST_NEW_ENV=123"),
1936 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}",
1942 #[cfg_attr(target_os = "vxworks", ignore)]
1943 fn test_add_to_env() {
1944 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1945 let output = String::from_utf8_lossy(&result.stdout).to_string();
1948 output.contains("RUN_TEST_NEW_ENV=123"),
1949 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}",
1955 #[cfg_attr(target_os = "vxworks", ignore)]
1956 fn test_capture_env_at_spawn() {
1959 let mut cmd = env_cmd();
1960 cmd.env("RUN_TEST_NEW_ENV1", "123");
1962 // This variable will not be present if the environment has already
1963 // been captured above.
1964 env::set_var("RUN_TEST_NEW_ENV2", "456");
1965 let result = cmd.output().unwrap();
1966 env::remove_var("RUN_TEST_NEW_ENV2");
1968 let output = String::from_utf8_lossy(&result.stdout).to_string();
1971 output.contains("RUN_TEST_NEW_ENV1=123"),
1972 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}",
1976 output.contains("RUN_TEST_NEW_ENV2=456"),
1977 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}",
1982 // Regression tests for #30858.
1984 fn test_interior_nul_in_progname_is_error() {
1985 match Command::new("has-some-\0\0s-inside").spawn() {
1986 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1992 fn test_interior_nul_in_arg_is_error() {
1993 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1994 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2000 fn test_interior_nul_in_args_is_error() {
2001 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
2002 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2008 fn test_interior_nul_in_current_dir_is_error() {
2009 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
2010 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2015 // Regression tests for #30862.
2017 #[cfg_attr(target_os = "vxworks", ignore)]
2018 fn test_interior_nul_in_env_key_is_error() {
2019 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
2020 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2026 #[cfg_attr(target_os = "vxworks", ignore)]
2027 fn test_interior_nul_in_env_value_is_error() {
2028 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
2029 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2034 /// Tests that process creation flags work by debugging a process.
2035 /// Other creation flags make it hard or impossible to detect
2036 /// behavioral changes in the process.
2039 fn test_creation_flags() {
2040 use crate::os::windows::process::CommandExt;
2041 use crate::sys::c::{BOOL, DWORD, INFINITE};
2043 struct DEBUG_EVENT {
2044 pub event_code: DWORD,
2045 pub process_id: DWORD,
2046 pub thread_id: DWORD,
2047 // This is a union in the real struct, but we don't
2048 // need this data for the purposes of this test.
2049 pub _junk: [u8; 164],
2053 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
2054 fn ContinueDebugEvent(
2057 dwContinueStatus: DWORD,
2061 const DEBUG_PROCESS: DWORD = 1;
2062 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
2063 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
2065 let mut child = Command::new("cmd")
2066 .creation_flags(DEBUG_PROCESS)
2067 .stdin(Stdio::piped())
2070 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
2072 let mut event = DEBUG_EVENT { event_code: 0, process_id: 0, thread_id: 0, _junk: [0; 164] };
2074 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
2075 panic!("WaitForDebugEvent failed!");
2079 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
2084 ContinueDebugEvent(event.process_id, event.thread_id, DBG_EXCEPTION_NOT_HANDLED)
2087 panic!("ContinueDebugEvent failed!");
2090 assert!(events > 0);
2094 fn test_command_implements_send() {
2095 fn take_send_type<T: Send>(_: T) {}
2096 take_send_type(Command::new(""))