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 is_write_vectored(&self) -> bool {
249 self.inner.is_write_vectored()
252 fn flush(&mut self) -> io::Result<()> {
257 impl AsInner<AnonPipe> for ChildStdin {
258 fn as_inner(&self) -> &AnonPipe {
263 impl IntoInner<AnonPipe> for ChildStdin {
264 fn into_inner(self) -> AnonPipe {
269 impl FromInner<AnonPipe> for ChildStdin {
270 fn from_inner(pipe: AnonPipe) -> ChildStdin {
271 ChildStdin { inner: pipe }
275 #[stable(feature = "std_debug", since = "1.16.0")]
276 impl fmt::Debug for ChildStdin {
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278 f.pad("ChildStdin { .. }")
282 /// A handle to a child process's standard output (stdout).
284 /// This struct is used in the [`stdout`] field on [`Child`].
286 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
287 /// underlying file handle will be closed.
289 /// [`Child`]: struct.Child.html
290 /// [`stdout`]: struct.Child.html#structfield.stdout
291 /// [dropped]: ../ops/trait.Drop.html
292 #[stable(feature = "process", since = "1.0.0")]
293 pub struct ChildStdout {
297 #[stable(feature = "process", since = "1.0.0")]
298 impl Read for ChildStdout {
299 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
303 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
304 self.inner.read_vectored(bufs)
308 fn is_read_vectored(&self) -> bool {
309 self.inner.is_read_vectored()
313 unsafe fn initializer(&self) -> Initializer {
318 impl AsInner<AnonPipe> for ChildStdout {
319 fn as_inner(&self) -> &AnonPipe {
324 impl IntoInner<AnonPipe> for ChildStdout {
325 fn into_inner(self) -> AnonPipe {
330 impl FromInner<AnonPipe> for ChildStdout {
331 fn from_inner(pipe: AnonPipe) -> ChildStdout {
332 ChildStdout { inner: pipe }
336 #[stable(feature = "std_debug", since = "1.16.0")]
337 impl fmt::Debug for ChildStdout {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 f.pad("ChildStdout { .. }")
343 /// A handle to a child process's stderr.
345 /// This struct is used in the [`stderr`] field on [`Child`].
347 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
348 /// underlying file handle will be closed.
350 /// [`Child`]: struct.Child.html
351 /// [`stderr`]: struct.Child.html#structfield.stderr
352 /// [dropped]: ../ops/trait.Drop.html
353 #[stable(feature = "process", since = "1.0.0")]
354 pub struct ChildStderr {
358 #[stable(feature = "process", since = "1.0.0")]
359 impl Read for ChildStderr {
360 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
364 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
365 self.inner.read_vectored(bufs)
369 fn is_read_vectored(&self) -> bool {
370 self.inner.is_read_vectored()
374 unsafe fn initializer(&self) -> Initializer {
379 impl AsInner<AnonPipe> for ChildStderr {
380 fn as_inner(&self) -> &AnonPipe {
385 impl IntoInner<AnonPipe> for ChildStderr {
386 fn into_inner(self) -> AnonPipe {
391 impl FromInner<AnonPipe> for ChildStderr {
392 fn from_inner(pipe: AnonPipe) -> ChildStderr {
393 ChildStderr { inner: pipe }
397 #[stable(feature = "std_debug", since = "1.16.0")]
398 impl fmt::Debug for ChildStderr {
399 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400 f.pad("ChildStderr { .. }")
404 /// A process builder, providing fine-grained control
405 /// over how a new process should be spawned.
407 /// A default configuration can be
408 /// generated using `Command::new(program)`, where `program` gives a path to the
409 /// program to be executed. Additional builder methods allow the configuration
410 /// to be changed (for example, by adding arguments) prior to spawning:
413 /// use std::process::Command;
415 /// let output = if cfg!(target_os = "windows") {
416 /// Command::new("cmd")
417 /// .args(&["/C", "echo hello"])
419 /// .expect("failed to execute process")
421 /// Command::new("sh")
423 /// .arg("echo hello")
425 /// .expect("failed to execute process")
428 /// let hello = output.stdout;
431 /// `Command` can be reused to spawn multiple processes. The builder methods
432 /// change the command without needing to immediately spawn the process.
435 /// use std::process::Command;
437 /// let mut echo_hello = Command::new("sh");
438 /// echo_hello.arg("-c")
439 /// .arg("echo hello");
440 /// let hello_1 = echo_hello.output().expect("failed to execute process");
441 /// let hello_2 = echo_hello.output().expect("failed to execute process");
444 /// Similarly, you can call builder methods after spawning a process and then
445 /// spawn a new process with the modified settings.
448 /// use std::process::Command;
450 /// let mut list_dir = Command::new("ls");
452 /// // Execute `ls` in the current directory of the program.
453 /// list_dir.status().expect("process failed to execute");
457 /// // Change `ls` to execute in the root directory.
458 /// list_dir.current_dir("/");
460 /// // And then execute `ls` again but in the root directory.
461 /// list_dir.status().expect("process failed to execute");
463 #[stable(feature = "process", since = "1.0.0")]
469 /// Constructs a new `Command` for launching the program at
470 /// path `program`, with the following default configuration:
472 /// * No arguments to the program
473 /// * Inherit the current process's environment
474 /// * Inherit the current process's working directory
475 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
477 /// Builder methods are provided to change these defaults and
478 /// otherwise configure the process.
480 /// If `program` is not an absolute path, the `PATH` will be searched in
481 /// an OS-defined way.
483 /// The search path to be used may be controlled by setting the
484 /// `PATH` environment variable on the Command,
485 /// but this has some implementation limitations on Windows
486 /// (see issue #37519).
493 /// use std::process::Command;
495 /// Command::new("sh")
497 /// .expect("sh command failed to start");
499 #[stable(feature = "process", since = "1.0.0")]
500 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
501 Command { inner: imp::Command::new(program.as_ref()) }
504 /// Adds an argument to pass to the program.
506 /// Only one argument can be passed per use. So instead of:
509 /// # std::process::Command::new("sh")
510 /// .arg("-C /path/to/repo")
517 /// # std::process::Command::new("sh")
519 /// .arg("/path/to/repo")
523 /// To pass multiple arguments see [`args`].
525 /// [`args`]: #method.args
532 /// use std::process::Command;
534 /// Command::new("ls")
538 /// .expect("ls command failed to start");
540 #[stable(feature = "process", since = "1.0.0")]
541 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
542 self.inner.arg(arg.as_ref());
546 /// Adds multiple arguments to pass to the program.
548 /// To pass a single argument see [`arg`].
550 /// [`arg`]: #method.arg
557 /// use std::process::Command;
559 /// Command::new("ls")
560 /// .args(&["-l", "-a"])
562 /// .expect("ls command failed to start");
564 #[stable(feature = "process", since = "1.0.0")]
565 pub fn args<I, S>(&mut self, args: I) -> &mut Command
567 I: IntoIterator<Item = S>,
571 self.arg(arg.as_ref());
576 /// Inserts or updates an environment variable mapping.
578 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
579 /// and case-sensitive on all other platforms.
586 /// use std::process::Command;
588 /// Command::new("ls")
589 /// .env("PATH", "/bin")
591 /// .expect("ls command failed to start");
593 #[stable(feature = "process", since = "1.0.0")]
594 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
599 self.inner.env_mut().set(key.as_ref(), val.as_ref());
603 /// Adds or updates multiple environment variable mappings.
610 /// use std::process::{Command, Stdio};
612 /// use std::collections::HashMap;
614 /// let filtered_env : HashMap<String, String> =
615 /// env::vars().filter(|&(ref k, _)|
616 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
619 /// Command::new("printenv")
620 /// .stdin(Stdio::null())
621 /// .stdout(Stdio::inherit())
623 /// .envs(&filtered_env)
625 /// .expect("printenv failed to start");
627 #[stable(feature = "command_envs", since = "1.19.0")]
628 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
630 I: IntoIterator<Item = (K, V)>,
634 for (ref key, ref val) in vars {
635 self.inner.env_mut().set(key.as_ref(), val.as_ref());
640 /// Removes an environment variable mapping.
647 /// use std::process::Command;
649 /// Command::new("ls")
650 /// .env_remove("PATH")
652 /// .expect("ls command failed to start");
654 #[stable(feature = "process", since = "1.0.0")]
655 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
656 self.inner.env_mut().remove(key.as_ref());
660 /// Clears the entire environment map for the child process.
667 /// use std::process::Command;
669 /// Command::new("ls")
672 /// .expect("ls command failed to start");
674 #[stable(feature = "process", since = "1.0.0")]
675 pub fn env_clear(&mut self) -> &mut Command {
676 self.inner.env_mut().clear();
680 /// Sets the working directory for the child process.
682 /// # Platform-specific behavior
684 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
685 /// whether it should be interpreted relative to the parent's working
686 /// directory or relative to `current_dir`. The behavior in this case is
687 /// platform specific and unstable, and it's recommended to use
688 /// [`canonicalize`] to get an absolute program path instead.
695 /// use std::process::Command;
697 /// Command::new("ls")
698 /// .current_dir("/bin")
700 /// .expect("ls command failed to start");
703 /// [`canonicalize`]: ../fs/fn.canonicalize.html
704 #[stable(feature = "process", since = "1.0.0")]
705 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
706 self.inner.cwd(dir.as_ref().as_ref());
710 /// Configuration for the child process's standard input (stdin) handle.
712 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
713 /// defaults to [`piped`] when used with `output`.
715 /// [`inherit`]: struct.Stdio.html#method.inherit
716 /// [`piped`]: struct.Stdio.html#method.piped
723 /// use std::process::{Command, Stdio};
725 /// Command::new("ls")
726 /// .stdin(Stdio::null())
728 /// .expect("ls command failed to start");
730 #[stable(feature = "process", since = "1.0.0")]
731 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
732 self.inner.stdin(cfg.into().0);
736 /// Configuration for the child process's standard output (stdout) handle.
738 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
739 /// defaults to [`piped`] when used with `output`.
741 /// [`inherit`]: struct.Stdio.html#method.inherit
742 /// [`piped`]: struct.Stdio.html#method.piped
749 /// use std::process::{Command, Stdio};
751 /// Command::new("ls")
752 /// .stdout(Stdio::null())
754 /// .expect("ls command failed to start");
756 #[stable(feature = "process", since = "1.0.0")]
757 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
758 self.inner.stdout(cfg.into().0);
762 /// Configuration for the child process's standard error (stderr) handle.
764 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
765 /// defaults to [`piped`] when used with `output`.
767 /// [`inherit`]: struct.Stdio.html#method.inherit
768 /// [`piped`]: struct.Stdio.html#method.piped
775 /// use std::process::{Command, Stdio};
777 /// Command::new("ls")
778 /// .stderr(Stdio::null())
780 /// .expect("ls command failed to start");
782 #[stable(feature = "process", since = "1.0.0")]
783 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
784 self.inner.stderr(cfg.into().0);
788 /// Executes the command as a child process, returning a handle to it.
790 /// By default, stdin, stdout and stderr are inherited from the parent.
797 /// use std::process::Command;
799 /// Command::new("ls")
801 /// .expect("ls command failed to start");
803 #[stable(feature = "process", since = "1.0.0")]
804 pub fn spawn(&mut self) -> io::Result<Child> {
805 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
808 /// Executes the command as a child process, waiting for it to finish and
809 /// collecting all of its output.
811 /// By default, stdout and stderr are captured (and used to provide the
812 /// resulting output). Stdin is not inherited from the parent and any
813 /// attempt by the child process to read from the stdin stream will result
814 /// in the stream immediately closing.
819 /// use std::process::Command;
820 /// use std::io::{self, Write};
821 /// let output = Command::new("/bin/cat")
824 /// .expect("failed to execute process");
826 /// println!("status: {}", output.status);
827 /// io::stdout().write_all(&output.stdout).unwrap();
828 /// io::stderr().write_all(&output.stderr).unwrap();
830 /// assert!(output.status.success());
832 #[stable(feature = "process", since = "1.0.0")]
833 pub fn output(&mut self) -> io::Result<Output> {
835 .spawn(imp::Stdio::MakePipe, false)
836 .map(Child::from_inner)
837 .and_then(|p| p.wait_with_output())
840 /// Executes a command as a child process, waiting for it to finish and
841 /// collecting its exit status.
843 /// By default, stdin, stdout and stderr are inherited from the parent.
848 /// use std::process::Command;
850 /// let status = Command::new("/bin/cat")
853 /// .expect("failed to execute process");
855 /// println!("process exited with: {}", status);
857 /// assert!(status.success());
859 #[stable(feature = "process", since = "1.0.0")]
860 pub fn status(&mut self) -> io::Result<ExitStatus> {
862 .spawn(imp::Stdio::Inherit, true)
863 .map(Child::from_inner)
864 .and_then(|mut p| p.wait())
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl fmt::Debug for Command {
870 /// Format the program and arguments of a Command for display. Any
871 /// non-utf8 data is lossily converted using the utf8 replacement
873 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
878 impl AsInner<imp::Command> for Command {
879 fn as_inner(&self) -> &imp::Command {
884 impl AsInnerMut<imp::Command> for Command {
885 fn as_inner_mut(&mut self) -> &mut imp::Command {
890 /// The output of a finished process.
892 /// This is returned in a Result by either the [`output`] method of a
893 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
896 /// [`Command`]: struct.Command.html
897 /// [`Child`]: struct.Child.html
898 /// [`output`]: struct.Command.html#method.output
899 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
900 #[derive(PartialEq, Eq, Clone)]
901 #[stable(feature = "process", since = "1.0.0")]
903 /// The status (exit code) of the process.
904 #[stable(feature = "process", since = "1.0.0")]
905 pub status: ExitStatus,
906 /// The data that the process wrote to stdout.
907 #[stable(feature = "process", since = "1.0.0")]
909 /// The data that the process wrote to stderr.
910 #[stable(feature = "process", since = "1.0.0")]
914 // If either stderr or stdout are valid utf8 strings it prints the valid
915 // strings, otherwise it prints the byte sequence instead
916 #[stable(feature = "process_output_debug", since = "1.7.0")]
917 impl fmt::Debug for Output {
918 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
919 let stdout_utf8 = str::from_utf8(&self.stdout);
920 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
922 Err(_) => &self.stdout,
925 let stderr_utf8 = str::from_utf8(&self.stderr);
926 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
928 Err(_) => &self.stderr,
931 fmt.debug_struct("Output")
932 .field("status", &self.status)
933 .field("stdout", stdout_debug)
934 .field("stderr", stderr_debug)
939 /// Describes what to do with a standard I/O stream for a child process when
940 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
942 /// [`stdin`]: struct.Command.html#method.stdin
943 /// [`stdout`]: struct.Command.html#method.stdout
944 /// [`stderr`]: struct.Command.html#method.stderr
945 /// [`Command`]: struct.Command.html
946 #[stable(feature = "process", since = "1.0.0")]
947 pub struct Stdio(imp::Stdio);
950 /// A new pipe should be arranged to connect the parent and child processes.
957 /// use std::process::{Command, Stdio};
959 /// let output = Command::new("echo")
960 /// .arg("Hello, world!")
961 /// .stdout(Stdio::piped())
963 /// .expect("Failed to execute command");
965 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
966 /// // Nothing echoed to console
972 /// use std::io::Write;
973 /// use std::process::{Command, Stdio};
975 /// let mut child = Command::new("rev")
976 /// .stdin(Stdio::piped())
977 /// .stdout(Stdio::piped())
979 /// .expect("Failed to spawn child process");
982 /// let stdin = child.stdin.as_mut().expect("Failed to open stdin");
983 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
986 /// let output = child.wait_with_output().expect("Failed to read stdout");
987 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
989 #[stable(feature = "process", since = "1.0.0")]
990 pub fn piped() -> Stdio {
991 Stdio(imp::Stdio::MakePipe)
994 /// The child inherits from the corresponding parent descriptor.
1001 /// use std::process::{Command, Stdio};
1003 /// let output = Command::new("echo")
1004 /// .arg("Hello, world!")
1005 /// .stdout(Stdio::inherit())
1007 /// .expect("Failed to execute command");
1009 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1010 /// // "Hello, world!" echoed to console
1016 /// use std::process::{Command, Stdio};
1017 /// use std::io::{self, Write};
1019 /// let output = Command::new("rev")
1020 /// .stdin(Stdio::inherit())
1021 /// .stdout(Stdio::piped())
1023 /// .expect("Failed to execute command");
1025 /// print!("You piped in the reverse of: ");
1026 /// io::stdout().write_all(&output.stdout).unwrap();
1028 #[stable(feature = "process", since = "1.0.0")]
1029 pub fn inherit() -> Stdio {
1030 Stdio(imp::Stdio::Inherit)
1033 /// This stream will be ignored. This is the equivalent of attaching the
1034 /// stream to `/dev/null`
1041 /// use std::process::{Command, Stdio};
1043 /// let output = Command::new("echo")
1044 /// .arg("Hello, world!")
1045 /// .stdout(Stdio::null())
1047 /// .expect("Failed to execute command");
1049 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1050 /// // Nothing echoed to console
1056 /// use std::process::{Command, Stdio};
1058 /// let output = Command::new("rev")
1059 /// .stdin(Stdio::null())
1060 /// .stdout(Stdio::piped())
1062 /// .expect("Failed to execute command");
1064 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1065 /// // Ignores any piped-in input
1067 #[stable(feature = "process", since = "1.0.0")]
1068 pub fn null() -> Stdio {
1069 Stdio(imp::Stdio::Null)
1073 impl FromInner<imp::Stdio> for Stdio {
1074 fn from_inner(inner: imp::Stdio) -> Stdio {
1079 #[stable(feature = "std_debug", since = "1.16.0")]
1080 impl fmt::Debug for Stdio {
1081 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082 f.pad("Stdio { .. }")
1086 #[stable(feature = "stdio_from", since = "1.20.0")]
1087 impl From<ChildStdin> for Stdio {
1088 /// Converts a `ChildStdin` into a `Stdio`
1092 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1095 /// use std::process::{Command, Stdio};
1097 /// let reverse = Command::new("rev")
1098 /// .stdin(Stdio::piped())
1100 /// .expect("failed reverse command");
1102 /// let _echo = Command::new("echo")
1103 /// .arg("Hello, world!")
1104 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1106 /// .expect("failed echo command");
1108 /// // "!dlrow ,olleH" echoed to console
1110 fn from(child: ChildStdin) -> Stdio {
1111 Stdio::from_inner(child.into_inner().into())
1115 #[stable(feature = "stdio_from", since = "1.20.0")]
1116 impl From<ChildStdout> for Stdio {
1117 /// Converts a `ChildStdout` into a `Stdio`
1121 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1124 /// use std::process::{Command, Stdio};
1126 /// let hello = Command::new("echo")
1127 /// .arg("Hello, world!")
1128 /// .stdout(Stdio::piped())
1130 /// .expect("failed echo command");
1132 /// let reverse = Command::new("rev")
1133 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1135 /// .expect("failed reverse command");
1137 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1139 fn from(child: ChildStdout) -> Stdio {
1140 Stdio::from_inner(child.into_inner().into())
1144 #[stable(feature = "stdio_from", since = "1.20.0")]
1145 impl From<ChildStderr> for Stdio {
1146 /// Converts a `ChildStderr` into a `Stdio`
1151 /// use std::process::{Command, Stdio};
1153 /// let reverse = Command::new("rev")
1154 /// .arg("non_existing_file.txt")
1155 /// .stderr(Stdio::piped())
1157 /// .expect("failed reverse command");
1159 /// let cat = Command::new("cat")
1161 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1163 /// .expect("failed echo command");
1166 /// String::from_utf8_lossy(&cat.stdout),
1167 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1170 fn from(child: ChildStderr) -> Stdio {
1171 Stdio::from_inner(child.into_inner().into())
1175 #[stable(feature = "stdio_from", since = "1.20.0")]
1176 impl From<fs::File> for Stdio {
1177 /// Converts a `File` into a `Stdio`
1181 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1184 /// use std::fs::File;
1185 /// use std::process::Command;
1187 /// // With the `foo.txt` file containing `Hello, world!"
1188 /// let file = File::open("foo.txt").unwrap();
1190 /// let reverse = Command::new("rev")
1191 /// .stdin(file) // Implicit File conversion into a Stdio
1193 /// .expect("failed reverse command");
1195 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1197 fn from(file: fs::File) -> Stdio {
1198 Stdio::from_inner(file.into_inner().into())
1202 /// Describes the result of a process after it has terminated.
1204 /// This `struct` is used to represent the exit status of a child process.
1205 /// Child processes are created via the [`Command`] struct and their exit
1206 /// status is exposed through the [`status`] method, or the [`wait`] method
1207 /// of a [`Child`] process.
1209 /// [`Command`]: struct.Command.html
1210 /// [`Child`]: struct.Child.html
1211 /// [`status`]: struct.Command.html#method.status
1212 /// [`wait`]: struct.Child.html#method.wait
1213 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1214 #[stable(feature = "process", since = "1.0.0")]
1215 pub struct ExitStatus(imp::ExitStatus);
1218 /// Was termination successful? Signal termination is not considered a
1219 /// success, and success is defined as a zero exit status.
1224 /// use std::process::Command;
1226 /// let status = Command::new("mkdir")
1227 /// .arg("projects")
1229 /// .expect("failed to execute mkdir");
1231 /// if status.success() {
1232 /// println!("'projects/' directory created");
1234 /// println!("failed to create 'projects/' directory");
1237 #[stable(feature = "process", since = "1.0.0")]
1238 pub fn success(&self) -> bool {
1242 /// Returns the exit code of the process, if any.
1244 /// On Unix, this will return `None` if the process was terminated
1245 /// by a signal; `std::os::unix` provides an extension trait for
1246 /// extracting the signal and other details from the `ExitStatus`.
1251 /// use std::process::Command;
1253 /// let status = Command::new("mkdir")
1254 /// .arg("projects")
1256 /// .expect("failed to execute mkdir");
1258 /// match status.code() {
1259 /// Some(code) => println!("Exited with status code: {}", code),
1260 /// None => println!("Process terminated by signal")
1263 #[stable(feature = "process", since = "1.0.0")]
1264 pub fn code(&self) -> Option<i32> {
1269 impl AsInner<imp::ExitStatus> for ExitStatus {
1270 fn as_inner(&self) -> &imp::ExitStatus {
1275 impl FromInner<imp::ExitStatus> for ExitStatus {
1276 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1281 #[stable(feature = "process", since = "1.0.0")]
1282 impl fmt::Display for ExitStatus {
1283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1288 /// This type represents the status code a process can return to its
1289 /// parent under normal termination.
1291 /// Numeric values used in this type don't have portable meanings, and
1292 /// different platforms may mask different amounts of them.
1294 /// For the platform's canonical successful and unsuccessful codes, see
1295 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1297 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1298 /// [`FAILURE`]: #associatedconstant.FAILURE
1300 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1301 /// it was ultimately cut from that RFC, and thus this type is more subject
1302 /// to change even than the usual unstable item churn.
1304 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1305 #[derive(Clone, Copy, Debug)]
1306 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1307 pub struct ExitCode(imp::ExitCode);
1309 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1311 /// The canonical ExitCode for successful termination on this platform.
1313 /// Note that a `()`-returning `main` implicitly results in a successful
1314 /// termination, so there's no need to return this from `main` unless
1315 /// you're also returning other possible codes.
1316 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1317 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1319 /// The canonical ExitCode for unsuccessful termination on this platform.
1321 /// If you're only returning this and `SUCCESS` from `main`, consider
1322 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1323 /// return the same codes (but will also `eprintln!` the error).
1324 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1325 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1329 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1330 /// error is returned.
1332 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1333 /// especially the [`Other`] kind might change to more specific kinds in the future.
1335 /// This is equivalent to sending a SIGKILL on Unix platforms.
1342 /// use std::process::Command;
1344 /// let mut command = Command::new("yes");
1345 /// if let Ok(mut child) = command.spawn() {
1346 /// child.kill().expect("command wasn't running");
1348 /// println!("yes command didn't start");
1352 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1353 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1354 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1355 #[stable(feature = "process", since = "1.0.0")]
1356 pub fn kill(&mut self) -> io::Result<()> {
1360 /// Returns the OS-assigned process identifier associated with this child.
1367 /// use std::process::Command;
1369 /// let mut command = Command::new("ls");
1370 /// if let Ok(child) = command.spawn() {
1371 /// println!("Child's ID is {}", child.id());
1373 /// println!("ls command didn't start");
1376 #[stable(feature = "process_id", since = "1.3.0")]
1377 pub fn id(&self) -> u32 {
1381 /// Waits for the child to exit completely, returning the status that it
1382 /// exited with. This function will continue to have the same return value
1383 /// after it has been called at least once.
1385 /// The stdin handle to the child process, if any, will be closed
1386 /// before waiting. This helps avoid deadlock: it ensures that the
1387 /// child does not block waiting for input from the parent, while
1388 /// the parent waits for the child to exit.
1395 /// use std::process::Command;
1397 /// let mut command = Command::new("ls");
1398 /// if let Ok(mut child) = command.spawn() {
1399 /// child.wait().expect("command wasn't running");
1400 /// println!("Child has finished its execution!");
1402 /// println!("ls command didn't start");
1405 #[stable(feature = "process", since = "1.0.0")]
1406 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1407 drop(self.stdin.take());
1408 self.handle.wait().map(ExitStatus)
1411 /// Attempts to collect the exit status of the child if it has already
1414 /// This function will not block the calling thread and will only
1415 /// check to see if the child process has exited or not. If the child has
1416 /// exited then on Unix the process ID is reaped. This function is
1417 /// guaranteed to repeatedly return a successful exit status so long as the
1418 /// child has already exited.
1420 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1421 /// exit status is not available at this time then `Ok(None)` is returned.
1422 /// If an error occurs, then that error is returned.
1424 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1431 /// use std::process::Command;
1433 /// let mut child = Command::new("ls").spawn().unwrap();
1435 /// match child.try_wait() {
1436 /// Ok(Some(status)) => println!("exited with: {}", status),
1438 /// println!("status not ready yet, let's really wait");
1439 /// let res = child.wait();
1440 /// println!("result: {:?}", res);
1442 /// Err(e) => println!("error attempting to wait: {}", e),
1445 #[stable(feature = "process_try_wait", since = "1.18.0")]
1446 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1447 Ok(self.handle.try_wait()?.map(ExitStatus))
1450 /// Simultaneously waits for the child to exit and collect all remaining
1451 /// output on the stdout/stderr handles, returning an `Output`
1454 /// The stdin handle to the child process, if any, will be closed
1455 /// before waiting. This helps avoid deadlock: it ensures that the
1456 /// child does not block waiting for input from the parent, while
1457 /// the parent waits for the child to exit.
1459 /// By default, stdin, stdout and stderr are inherited from the parent.
1460 /// In order to capture the output into this `Result<Output>` it is
1461 /// necessary to create new pipes between parent and child. Use
1462 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1467 /// use std::process::{Command, Stdio};
1469 /// let child = Command::new("/bin/cat")
1470 /// .arg("file.txt")
1471 /// .stdout(Stdio::piped())
1473 /// .expect("failed to execute child");
1475 /// let output = child
1476 /// .wait_with_output()
1477 /// .expect("failed to wait on child");
1479 /// assert!(output.status.success());
1482 #[stable(feature = "process", since = "1.0.0")]
1483 pub fn wait_with_output(mut self) -> io::Result<Output> {
1484 drop(self.stdin.take());
1486 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1487 match (self.stdout.take(), self.stderr.take()) {
1489 (Some(mut out), None) => {
1490 let res = out.read_to_end(&mut stdout);
1493 (None, Some(mut err)) => {
1494 let res = err.read_to_end(&mut stderr);
1497 (Some(out), Some(err)) => {
1498 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1503 let status = self.wait()?;
1504 Ok(Output { status, stdout, stderr })
1508 /// Terminates the current process with the specified exit code.
1510 /// This function will never return and will immediately terminate the current
1511 /// process. The exit code is passed through to the underlying OS and will be
1512 /// available for consumption by another process.
1514 /// Note that because this function never returns, and that it terminates the
1515 /// process, no destructors on the current stack or any other thread's stack
1516 /// will be run. If a clean shutdown is needed it is recommended to only call
1517 /// this function at a known point where there are no more destructors left
1520 /// ## Platform-specific behavior
1522 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1523 /// will be visible to a parent process inspecting the exit code. On most
1524 /// Unix-like platforms, only the eight least-significant bits are considered.
1528 /// Due to this function’s behavior regarding destructors, a conventional way
1529 /// to use the function is to extract the actual computation to another
1530 /// function and compute the exit code from its return value:
1533 /// fn run_app() -> Result<(), ()> {
1534 /// // Application logic here
1539 /// std::process::exit(match run_app() {
1542 /// eprintln!("error: {:?}", err);
1549 /// Due to [platform-specific behavior], the exit code for this example will be
1550 /// `0` on Linux, but `256` on Windows:
1553 /// use std::process;
1555 /// process::exit(0x0100);
1558 /// [platform-specific behavior]: #platform-specific-behavior
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 pub fn exit(code: i32) -> ! {
1561 crate::sys_common::cleanup();
1562 crate::sys::os::exit(code)
1565 /// Terminates the process in an abnormal fashion.
1567 /// The function will never return and will immediately terminate the current
1568 /// process in a platform specific "abnormal" manner.
1570 /// Note that because this function never returns, and that it terminates the
1571 /// process, no destructors on the current stack or any other thread's stack
1574 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1575 /// the current thread's stack and calls all destructors.
1576 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1577 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1578 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1580 /// If a clean shutdown is needed it is recommended to only call
1581 /// this function at a known point where there are no more destructors left
1587 /// use std::process;
1590 /// println!("aborting");
1592 /// process::abort();
1594 /// // execution never gets here
1598 /// The `abort` function terminates the process, so the destructor will not
1599 /// get run on the example below:
1602 /// use std::process;
1606 /// impl Drop for HasDrop {
1607 /// fn drop(&mut self) {
1608 /// println!("This will never be printed!");
1613 /// let _x = HasDrop;
1614 /// process::abort();
1615 /// // the destructor implemented for HasDrop will never get run
1619 /// [`panic!`]: ../../std/macro.panic.html
1620 /// [panic hook]: ../../std/panic/fn.set_hook.html
1621 #[stable(feature = "process_abort", since = "1.17.0")]
1622 pub fn abort() -> ! {
1623 crate::sys::abort_internal();
1626 /// Returns the OS-assigned process identifier associated with this process.
1633 /// use std::process;
1635 /// println!("My pid is {}", process::id());
1639 #[stable(feature = "getpid", since = "1.26.0")]
1640 pub fn id() -> u32 {
1641 crate::sys::os::getpid()
1644 /// A trait for implementing arbitrary return types in the `main` function.
1646 /// The C-main function only supports to return integers as return type.
1647 /// So, every type implementing the `Termination` trait has to be converted
1650 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1651 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1652 #[cfg_attr(not(test), lang = "termination")]
1653 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1654 #[rustc_on_unimplemented(
1655 message = "`main` has invalid return type `{Self}`",
1656 label = "`main` can only return types that implement `{Termination}`"
1658 pub trait Termination {
1659 /// Is called to get the representation of the value as status code.
1660 /// This status code is returned to the operating system.
1661 fn report(self) -> i32;
1664 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1665 impl Termination for () {
1667 fn report(self) -> i32 {
1668 ExitCode::SUCCESS.report()
1672 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1673 impl<E: fmt::Debug> Termination for Result<(), E> {
1674 fn report(self) -> i32 {
1676 Ok(()) => ().report(),
1677 Err(err) => Err::<!, _>(err).report(),
1682 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1683 impl Termination for ! {
1684 fn report(self) -> i32 {
1689 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1690 impl<E: fmt::Debug> Termination for Result<!, E> {
1691 fn report(self) -> i32 {
1692 let Err(err) = self;
1693 eprintln!("Error: {:?}", err);
1694 ExitCode::FAILURE.report()
1698 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1699 impl Termination for ExitCode {
1701 fn report(self) -> i32 {
1706 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
1708 use crate::io::prelude::*;
1710 use super::{Command, Output, Stdio};
1711 use crate::io::ErrorKind;
1714 // FIXME(#10380) these tests should not all be ignored on android.
1717 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1719 let p = if cfg!(target_os = "windows") {
1720 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1722 Command::new("true").spawn()
1725 let mut p = p.unwrap();
1726 assert!(p.wait().unwrap().success());
1730 #[cfg_attr(target_os = "android", ignore)]
1731 fn smoke_failure() {
1732 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1739 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1740 fn exit_reported_right() {
1741 let p = if cfg!(target_os = "windows") {
1742 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1744 Command::new("false").spawn()
1747 let mut p = p.unwrap();
1748 assert!(p.wait().unwrap().code() == Some(1));
1754 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1755 fn signal_reported_right() {
1756 use crate::os::unix::process::ExitStatusExt;
1759 Command::new("/bin/sh").arg("-c").arg("read a").stdin(Stdio::piped()).spawn().unwrap();
1761 match p.wait().unwrap().signal() {
1763 result => panic!("not terminated by signal 9 (instead, {:?})", result),
1767 pub fn run_output(mut cmd: Command) -> String {
1768 let p = cmd.spawn();
1770 let mut p = p.unwrap();
1771 assert!(p.stdout.is_some());
1772 let mut ret = String::new();
1773 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1774 assert!(p.wait().unwrap().success());
1779 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1781 if cfg!(target_os = "windows") {
1782 let mut cmd = Command::new("cmd");
1783 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1784 assert_eq!(run_output(cmd), "foobar\r\n");
1786 let mut cmd = Command::new("echo");
1787 cmd.arg("foobar").stdout(Stdio::piped());
1788 assert_eq!(run_output(cmd), "foobar\n");
1793 #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
1794 fn set_current_dir_works() {
1795 let mut cmd = Command::new("/bin/sh");
1796 cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped());
1797 assert_eq!(run_output(cmd), "/\n");
1801 #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
1803 let mut p = Command::new("/bin/sh")
1805 .arg("read line; echo $line")
1806 .stdin(Stdio::piped())
1807 .stdout(Stdio::piped())
1810 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1811 drop(p.stdin.take());
1812 let mut out = String::new();
1813 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1814 assert!(p.wait().unwrap().success());
1815 assert_eq!(out, "foobar\n");
1819 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1820 fn test_process_status() {
1821 let mut status = if cfg!(target_os = "windows") {
1822 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1824 Command::new("false").status().unwrap()
1826 assert!(status.code() == Some(1));
1828 status = if cfg!(target_os = "windows") {
1829 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1831 Command::new("true").status().unwrap()
1833 assert!(status.success());
1837 fn test_process_output_fail_to_start() {
1838 match Command::new("/no-binary-by-this-name-should-exist").output() {
1839 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1845 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1846 fn test_process_output_output() {
1847 let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
1848 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1850 Command::new("echo").arg("hello").output().unwrap()
1852 let output_str = str::from_utf8(&stdout).unwrap();
1854 assert!(status.success());
1855 assert_eq!(output_str.trim().to_string(), "hello");
1856 assert_eq!(stderr, Vec::new());
1860 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1861 fn test_process_output_error() {
1862 let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
1863 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1865 Command::new("mkdir").arg("./").output().unwrap()
1868 assert!(status.code() == Some(1));
1869 assert_eq!(stdout, Vec::new());
1870 assert!(!stderr.is_empty());
1874 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1875 fn test_finish_once() {
1876 let mut prog = if cfg!(target_os = "windows") {
1877 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1879 Command::new("false").spawn().unwrap()
1881 assert!(prog.wait().unwrap().code() == Some(1));
1885 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1886 fn test_finish_twice() {
1887 let mut prog = if cfg!(target_os = "windows") {
1888 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1890 Command::new("false").spawn().unwrap()
1892 assert!(prog.wait().unwrap().code() == Some(1));
1893 assert!(prog.wait().unwrap().code() == Some(1));
1897 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1898 fn test_wait_with_output_once() {
1899 let prog = if cfg!(target_os = "windows") {
1900 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1902 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1905 let Output { status, stdout, stderr } = prog.wait_with_output().unwrap();
1906 let output_str = str::from_utf8(&stdout).unwrap();
1908 assert!(status.success());
1909 assert_eq!(output_str.trim().to_string(), "hello");
1910 assert_eq!(stderr, Vec::new());
1913 #[cfg(all(unix, not(target_os = "android")))]
1914 pub fn env_cmd() -> Command {
1917 #[cfg(target_os = "android")]
1918 pub fn env_cmd() -> Command {
1919 let mut cmd = Command::new("/system/bin/sh");
1920 cmd.arg("-c").arg("set");
1925 pub fn env_cmd() -> Command {
1926 let mut cmd = Command::new("cmd");
1927 cmd.arg("/c").arg("set");
1932 #[cfg_attr(target_os = "vxworks", ignore)]
1933 fn test_override_env() {
1936 // In some build environments (such as chrooted Nix builds), `env` can
1937 // only be found in the explicitly-provided PATH env variable, not in
1938 // default places such as /bin or /usr/bin. So we need to pass through
1939 // PATH to our sub-process.
1940 let mut cmd = env_cmd();
1941 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1942 if let Some(p) = env::var_os("PATH") {
1943 cmd.env("PATH", &p);
1945 let result = cmd.output().unwrap();
1946 let output = String::from_utf8_lossy(&result.stdout).to_string();
1949 output.contains("RUN_TEST_NEW_ENV=123"),
1950 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}",
1956 #[cfg_attr(target_os = "vxworks", ignore)]
1957 fn test_add_to_env() {
1958 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1959 let output = String::from_utf8_lossy(&result.stdout).to_string();
1962 output.contains("RUN_TEST_NEW_ENV=123"),
1963 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}",
1969 #[cfg_attr(target_os = "vxworks", ignore)]
1970 fn test_capture_env_at_spawn() {
1973 let mut cmd = env_cmd();
1974 cmd.env("RUN_TEST_NEW_ENV1", "123");
1976 // This variable will not be present if the environment has already
1977 // been captured above.
1978 env::set_var("RUN_TEST_NEW_ENV2", "456");
1979 let result = cmd.output().unwrap();
1980 env::remove_var("RUN_TEST_NEW_ENV2");
1982 let output = String::from_utf8_lossy(&result.stdout).to_string();
1985 output.contains("RUN_TEST_NEW_ENV1=123"),
1986 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}",
1990 output.contains("RUN_TEST_NEW_ENV2=456"),
1991 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}",
1996 // Regression tests for #30858.
1998 fn test_interior_nul_in_progname_is_error() {
1999 match Command::new("has-some-\0\0s-inside").spawn() {
2000 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2006 fn test_interior_nul_in_arg_is_error() {
2007 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
2008 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2014 fn test_interior_nul_in_args_is_error() {
2015 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
2016 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2022 fn test_interior_nul_in_current_dir_is_error() {
2023 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
2024 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2029 // Regression tests for #30862.
2031 #[cfg_attr(target_os = "vxworks", ignore)]
2032 fn test_interior_nul_in_env_key_is_error() {
2033 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
2034 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2040 #[cfg_attr(target_os = "vxworks", ignore)]
2041 fn test_interior_nul_in_env_value_is_error() {
2042 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
2043 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2048 /// Tests that process creation flags work by debugging a process.
2049 /// Other creation flags make it hard or impossible to detect
2050 /// behavioral changes in the process.
2053 fn test_creation_flags() {
2054 use crate::os::windows::process::CommandExt;
2055 use crate::sys::c::{BOOL, DWORD, INFINITE};
2057 struct DEBUG_EVENT {
2058 pub event_code: DWORD,
2059 pub process_id: DWORD,
2060 pub thread_id: DWORD,
2061 // This is a union in the real struct, but we don't
2062 // need this data for the purposes of this test.
2063 pub _junk: [u8; 164],
2067 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
2068 fn ContinueDebugEvent(
2071 dwContinueStatus: DWORD,
2075 const DEBUG_PROCESS: DWORD = 1;
2076 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
2077 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
2079 let mut child = Command::new("cmd")
2080 .creation_flags(DEBUG_PROCESS)
2081 .stdin(Stdio::piped())
2084 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
2086 let mut event = DEBUG_EVENT { event_code: 0, process_id: 0, thread_id: 0, _junk: [0; 164] };
2088 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
2089 panic!("WaitForDebugEvent failed!");
2093 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
2098 ContinueDebugEvent(event.process_id, event.thread_id, DBG_EXCEPTION_NOT_HANDLED)
2101 panic!("ContinueDebugEvent failed!");
2104 assert!(events > 0);
2108 fn test_command_implements_send_sync() {
2109 fn take_send_sync_type<T: Send + Sync>(_: T) {}
2110 take_send_sync_type(Command::new(""))