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 { &self.handle }
192 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
193 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
196 stdin: io.stdin.map(ChildStdin::from_inner),
197 stdout: io.stdout.map(ChildStdout::from_inner),
198 stderr: io.stderr.map(ChildStderr::from_inner),
203 impl IntoInner<imp::Process> for Child {
204 fn into_inner(self) -> imp::Process { self.handle }
207 #[stable(feature = "std_debug", since = "1.16.0")]
208 impl fmt::Debug for Child {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.debug_struct("Child")
211 .field("stdin", &self.stdin)
212 .field("stdout", &self.stdout)
213 .field("stderr", &self.stderr)
218 /// A handle to a child process's standard input (stdin).
220 /// This struct is used in the [`stdin`] field on [`Child`].
222 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
223 /// file handle will be closed. If the child process was blocked on input prior
224 /// to being dropped, it will become unblocked after dropping.
226 /// [`Child`]: struct.Child.html
227 /// [`stdin`]: struct.Child.html#structfield.stdin
228 /// [dropped]: ../ops/trait.Drop.html
229 #[stable(feature = "process", since = "1.0.0")]
230 pub struct ChildStdin {
234 #[stable(feature = "process", since = "1.0.0")]
235 impl Write for ChildStdin {
236 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
237 self.inner.write(buf)
240 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
241 self.inner.write_vectored(bufs)
244 fn flush(&mut self) -> io::Result<()> {
249 impl AsInner<AnonPipe> for ChildStdin {
250 fn as_inner(&self) -> &AnonPipe { &self.inner }
253 impl IntoInner<AnonPipe> for ChildStdin {
254 fn into_inner(self) -> AnonPipe { self.inner }
257 impl FromInner<AnonPipe> for ChildStdin {
258 fn from_inner(pipe: AnonPipe) -> ChildStdin {
259 ChildStdin { inner: pipe }
263 #[stable(feature = "std_debug", since = "1.16.0")]
264 impl fmt::Debug for ChildStdin {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.pad("ChildStdin { .. }")
270 /// A handle to a child process's standard output (stdout).
272 /// This struct is used in the [`stdout`] field on [`Child`].
274 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
275 /// underlying file handle will be closed.
277 /// [`Child`]: struct.Child.html
278 /// [`stdout`]: struct.Child.html#structfield.stdout
279 /// [dropped]: ../ops/trait.Drop.html
280 #[stable(feature = "process", since = "1.0.0")]
281 pub struct ChildStdout {
285 #[stable(feature = "process", since = "1.0.0")]
286 impl Read for ChildStdout {
287 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
291 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
292 self.inner.read_vectored(bufs)
296 unsafe fn initializer(&self) -> Initializer {
301 impl AsInner<AnonPipe> for ChildStdout {
302 fn as_inner(&self) -> &AnonPipe { &self.inner }
305 impl IntoInner<AnonPipe> for ChildStdout {
306 fn into_inner(self) -> AnonPipe { self.inner }
309 impl FromInner<AnonPipe> for ChildStdout {
310 fn from_inner(pipe: AnonPipe) -> ChildStdout {
311 ChildStdout { inner: pipe }
315 #[stable(feature = "std_debug", since = "1.16.0")]
316 impl fmt::Debug for ChildStdout {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 f.pad("ChildStdout { .. }")
322 /// A handle to a child process's stderr.
324 /// This struct is used in the [`stderr`] field on [`Child`].
326 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
327 /// underlying file handle will be closed.
329 /// [`Child`]: struct.Child.html
330 /// [`stderr`]: struct.Child.html#structfield.stderr
331 /// [dropped]: ../ops/trait.Drop.html
332 #[stable(feature = "process", since = "1.0.0")]
333 pub struct ChildStderr {
337 #[stable(feature = "process", since = "1.0.0")]
338 impl Read for ChildStderr {
339 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
343 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
344 self.inner.read_vectored(bufs)
348 unsafe fn initializer(&self) -> Initializer {
353 impl AsInner<AnonPipe> for ChildStderr {
354 fn as_inner(&self) -> &AnonPipe { &self.inner }
357 impl IntoInner<AnonPipe> for ChildStderr {
358 fn into_inner(self) -> AnonPipe { self.inner }
361 impl FromInner<AnonPipe> for ChildStderr {
362 fn from_inner(pipe: AnonPipe) -> ChildStderr {
363 ChildStderr { inner: pipe }
367 #[stable(feature = "std_debug", since = "1.16.0")]
368 impl fmt::Debug for ChildStderr {
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 f.pad("ChildStderr { .. }")
374 /// A process builder, providing fine-grained control
375 /// over how a new process should be spawned.
377 /// A default configuration can be
378 /// generated using `Command::new(program)`, where `program` gives a path to the
379 /// program to be executed. Additional builder methods allow the configuration
380 /// to be changed (for example, by adding arguments) prior to spawning:
383 /// use std::process::Command;
385 /// let output = if cfg!(target_os = "windows") {
386 /// Command::new("cmd")
387 /// .args(&["/C", "echo hello"])
389 /// .expect("failed to execute process")
391 /// Command::new("sh")
393 /// .arg("echo hello")
395 /// .expect("failed to execute process")
398 /// let hello = output.stdout;
401 /// `Command` can be reused to spawn multiple processes. The builder methods
402 /// change the command without needing to immediately spawn the process.
405 /// use std::process::Command;
407 /// let mut echo_hello = Command::new("sh");
408 /// echo_hello.arg("-c")
409 /// .arg("echo hello");
410 /// let hello_1 = echo_hello.output().expect("failed to execute process");
411 /// let hello_2 = echo_hello.output().expect("failed to execute process");
414 /// Similarly, you can call builder methods after spawning a process and then
415 /// spawn a new process with the modified settings.
418 /// use std::process::Command;
420 /// let mut list_dir = Command::new("ls");
422 /// // Execute `ls` in the current directory of the program.
423 /// list_dir.status().expect("process failed to execute");
427 /// // Change `ls` to execute in the root directory.
428 /// list_dir.current_dir("/");
430 /// // And then execute `ls` again but in the root directory.
431 /// list_dir.status().expect("process failed to execute");
433 #[stable(feature = "process", since = "1.0.0")]
439 /// Constructs a new `Command` for launching the program at
440 /// path `program`, with the following default configuration:
442 /// * No arguments to the program
443 /// * Inherit the current process's environment
444 /// * Inherit the current process's working directory
445 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
447 /// Builder methods are provided to change these defaults and
448 /// otherwise configure the process.
450 /// If `program` is not an absolute path, the `PATH` will be searched in
451 /// an OS-defined way.
453 /// The search path to be used may be controlled by setting the
454 /// `PATH` environment variable on the Command,
455 /// but this has some implementation limitations on Windows
456 /// (see issue #37519).
463 /// use std::process::Command;
465 /// Command::new("sh")
467 /// .expect("sh command failed to start");
469 #[stable(feature = "process", since = "1.0.0")]
470 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
471 Command { inner: imp::Command::new(program.as_ref()) }
474 /// Adds an argument to pass to the program.
476 /// Only one argument can be passed per use. So instead of:
479 /// # std::process::Command::new("sh")
480 /// .arg("-C /path/to/repo")
487 /// # std::process::Command::new("sh")
489 /// .arg("/path/to/repo")
493 /// To pass multiple arguments see [`args`].
495 /// [`args`]: #method.args
502 /// use std::process::Command;
504 /// Command::new("ls")
508 /// .expect("ls command failed to start");
510 #[stable(feature = "process", since = "1.0.0")]
511 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
512 self.inner.arg(arg.as_ref());
516 /// Adds multiple arguments to pass to the program.
518 /// To pass a single argument see [`arg`].
520 /// [`arg`]: #method.arg
527 /// use std::process::Command;
529 /// Command::new("ls")
530 /// .args(&["-l", "-a"])
532 /// .expect("ls command failed to start");
534 #[stable(feature = "process", since = "1.0.0")]
535 pub fn args<I, S>(&mut self, args: I) -> &mut Command
536 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
539 self.arg(arg.as_ref());
544 /// Inserts or updates an environment variable mapping.
546 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
547 /// and case-sensitive on all other platforms.
554 /// use std::process::Command;
556 /// Command::new("ls")
557 /// .env("PATH", "/bin")
559 /// .expect("ls command failed to start");
561 #[stable(feature = "process", since = "1.0.0")]
562 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
563 where K: AsRef<OsStr>, V: AsRef<OsStr>
565 self.inner.env_mut().set(key.as_ref(), val.as_ref());
569 /// Adds or updates multiple environment variable mappings.
576 /// use std::process::{Command, Stdio};
578 /// use std::collections::HashMap;
580 /// let filtered_env : HashMap<String, String> =
581 /// env::vars().filter(|&(ref k, _)|
582 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
585 /// Command::new("printenv")
586 /// .stdin(Stdio::null())
587 /// .stdout(Stdio::inherit())
589 /// .envs(&filtered_env)
591 /// .expect("printenv failed to start");
593 #[stable(feature = "command_envs", since = "1.19.0")]
594 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
595 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
597 for (ref key, ref val) in vars {
598 self.inner.env_mut().set(key.as_ref(), val.as_ref());
603 /// Removes an environment variable mapping.
610 /// use std::process::Command;
612 /// Command::new("ls")
613 /// .env_remove("PATH")
615 /// .expect("ls command failed to start");
617 #[stable(feature = "process", since = "1.0.0")]
618 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
619 self.inner.env_mut().remove(key.as_ref());
623 /// Clears the entire environment map for the child process.
630 /// use std::process::Command;
632 /// Command::new("ls")
635 /// .expect("ls command failed to start");
637 #[stable(feature = "process", since = "1.0.0")]
638 pub fn env_clear(&mut self) -> &mut Command {
639 self.inner.env_mut().clear();
643 /// Sets the working directory for the child process.
645 /// # Platform-specific behavior
647 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
648 /// whether it should be interpreted relative to the parent's working
649 /// directory or relative to `current_dir`. The behavior in this case is
650 /// platform specific and unstable, and it's recommended to use
651 /// [`canonicalize`] to get an absolute program path instead.
658 /// use std::process::Command;
660 /// Command::new("ls")
661 /// .current_dir("/bin")
663 /// .expect("ls command failed to start");
666 /// [`canonicalize`]: ../fs/fn.canonicalize.html
667 #[stable(feature = "process", since = "1.0.0")]
668 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
669 self.inner.cwd(dir.as_ref().as_ref());
673 /// Configuration for the child process's standard input (stdin) handle.
675 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
676 /// defaults to [`piped`] when used with `output`.
678 /// [`inherit`]: struct.Stdio.html#method.inherit
679 /// [`piped`]: struct.Stdio.html#method.piped
686 /// use std::process::{Command, Stdio};
688 /// Command::new("ls")
689 /// .stdin(Stdio::null())
691 /// .expect("ls command failed to start");
693 #[stable(feature = "process", since = "1.0.0")]
694 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
695 self.inner.stdin(cfg.into().0);
699 /// Configuration for the child process's standard output (stdout) handle.
701 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
702 /// defaults to [`piped`] when used with `output`.
704 /// [`inherit`]: struct.Stdio.html#method.inherit
705 /// [`piped`]: struct.Stdio.html#method.piped
712 /// use std::process::{Command, Stdio};
714 /// Command::new("ls")
715 /// .stdout(Stdio::null())
717 /// .expect("ls command failed to start");
719 #[stable(feature = "process", since = "1.0.0")]
720 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
721 self.inner.stdout(cfg.into().0);
725 /// Configuration for the child process's standard error (stderr) handle.
727 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
728 /// defaults to [`piped`] when used with `output`.
730 /// [`inherit`]: struct.Stdio.html#method.inherit
731 /// [`piped`]: struct.Stdio.html#method.piped
738 /// use std::process::{Command, Stdio};
740 /// Command::new("ls")
741 /// .stderr(Stdio::null())
743 /// .expect("ls command failed to start");
745 #[stable(feature = "process", since = "1.0.0")]
746 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
747 self.inner.stderr(cfg.into().0);
751 /// Executes the command as a child process, returning a handle to it.
753 /// By default, stdin, stdout and stderr are inherited from the parent.
760 /// use std::process::Command;
762 /// Command::new("ls")
764 /// .expect("ls command failed to start");
766 #[stable(feature = "process", since = "1.0.0")]
767 pub fn spawn(&mut self) -> io::Result<Child> {
768 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
771 /// Executes the command as a child process, waiting for it to finish and
772 /// collecting all of its output.
774 /// By default, stdout and stderr are captured (and used to provide the
775 /// resulting output). Stdin is not inherited from the parent and any
776 /// attempt by the child process to read from the stdin stream will result
777 /// in the stream immediately closing.
782 /// use std::process::Command;
783 /// use std::io::{self, Write};
784 /// let output = Command::new("/bin/cat")
787 /// .expect("failed to execute process");
789 /// println!("status: {}", output.status);
790 /// io::stdout().write_all(&output.stdout).unwrap();
791 /// io::stderr().write_all(&output.stderr).unwrap();
793 /// assert!(output.status.success());
795 #[stable(feature = "process", since = "1.0.0")]
796 pub fn output(&mut self) -> io::Result<Output> {
797 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
798 .and_then(|p| p.wait_with_output())
801 /// Executes a command as a child process, waiting for it to finish and
802 /// collecting its exit status.
804 /// By default, stdin, stdout and stderr are inherited from the parent.
809 /// use std::process::Command;
811 /// let status = Command::new("/bin/cat")
814 /// .expect("failed to execute process");
816 /// println!("process exited with: {}", status);
818 /// assert!(status.success());
820 #[stable(feature = "process", since = "1.0.0")]
821 pub fn status(&mut self) -> io::Result<ExitStatus> {
822 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
823 .and_then(|mut p| p.wait())
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl fmt::Debug for Command {
829 /// Format the program and arguments of a Command for display. Any
830 /// non-utf8 data is lossily converted using the utf8 replacement
832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837 impl AsInner<imp::Command> for Command {
838 fn as_inner(&self) -> &imp::Command { &self.inner }
841 impl AsInnerMut<imp::Command> for Command {
842 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
845 /// The output of a finished process.
847 /// This is returned in a Result by either the [`output`] method of a
848 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
851 /// [`Command`]: struct.Command.html
852 /// [`Child`]: struct.Child.html
853 /// [`output`]: struct.Command.html#method.output
854 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
855 #[derive(PartialEq, Eq, Clone)]
856 #[stable(feature = "process", since = "1.0.0")]
858 /// The status (exit code) of the process.
859 #[stable(feature = "process", since = "1.0.0")]
860 pub status: ExitStatus,
861 /// The data that the process wrote to stdout.
862 #[stable(feature = "process", since = "1.0.0")]
864 /// The data that the process wrote to stderr.
865 #[stable(feature = "process", since = "1.0.0")]
869 // If either stderr or stdout are valid utf8 strings it prints the valid
870 // strings, otherwise it prints the byte sequence instead
871 #[stable(feature = "process_output_debug", since = "1.7.0")]
872 impl fmt::Debug for Output {
873 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
875 let stdout_utf8 = str::from_utf8(&self.stdout);
876 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
878 Err(_) => &self.stdout
881 let stderr_utf8 = str::from_utf8(&self.stderr);
882 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
884 Err(_) => &self.stderr
887 fmt.debug_struct("Output")
888 .field("status", &self.status)
889 .field("stdout", stdout_debug)
890 .field("stderr", stderr_debug)
895 /// Describes what to do with a standard I/O stream for a child process when
896 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
898 /// [`stdin`]: struct.Command.html#method.stdin
899 /// [`stdout`]: struct.Command.html#method.stdout
900 /// [`stderr`]: struct.Command.html#method.stderr
901 /// [`Command`]: struct.Command.html
902 #[stable(feature = "process", since = "1.0.0")]
903 pub struct Stdio(imp::Stdio);
906 /// A new pipe should be arranged to connect the parent and child processes.
913 /// use std::process::{Command, Stdio};
915 /// let output = Command::new("echo")
916 /// .arg("Hello, world!")
917 /// .stdout(Stdio::piped())
919 /// .expect("Failed to execute command");
921 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
922 /// // Nothing echoed to console
928 /// use std::io::Write;
929 /// use std::process::{Command, Stdio};
931 /// let mut child = Command::new("rev")
932 /// .stdin(Stdio::piped())
933 /// .stdout(Stdio::piped())
935 /// .expect("Failed to spawn child process");
938 /// let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
939 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
942 /// let output = child.wait_with_output().expect("Failed to read stdout");
943 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
945 #[stable(feature = "process", since = "1.0.0")]
946 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
948 /// The child inherits from the corresponding parent descriptor.
955 /// use std::process::{Command, Stdio};
957 /// let output = Command::new("echo")
958 /// .arg("Hello, world!")
959 /// .stdout(Stdio::inherit())
961 /// .expect("Failed to execute command");
963 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
964 /// // "Hello, world!" echoed to console
970 /// use std::process::{Command, Stdio};
971 /// use std::io::{self, Write};
973 /// let output = Command::new("rev")
974 /// .stdin(Stdio::inherit())
975 /// .stdout(Stdio::piped())
977 /// .expect("Failed to execute command");
979 /// print!("You piped in the reverse of: ");
980 /// io::stdout().write_all(&output.stdout).unwrap();
982 #[stable(feature = "process", since = "1.0.0")]
983 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
985 /// This stream will be ignored. This is the equivalent of attaching the
986 /// stream to `/dev/null`
993 /// use std::process::{Command, Stdio};
995 /// let output = Command::new("echo")
996 /// .arg("Hello, world!")
997 /// .stdout(Stdio::null())
999 /// .expect("Failed to execute command");
1001 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1002 /// // Nothing echoed to console
1008 /// use std::process::{Command, Stdio};
1010 /// let output = Command::new("rev")
1011 /// .stdin(Stdio::null())
1012 /// .stdout(Stdio::piped())
1014 /// .expect("Failed to execute command");
1016 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1017 /// // Ignores any piped-in input
1019 #[stable(feature = "process", since = "1.0.0")]
1020 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
1023 impl FromInner<imp::Stdio> for Stdio {
1024 fn from_inner(inner: imp::Stdio) -> Stdio {
1029 #[stable(feature = "std_debug", since = "1.16.0")]
1030 impl fmt::Debug for Stdio {
1031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1032 f.pad("Stdio { .. }")
1036 #[stable(feature = "stdio_from", since = "1.20.0")]
1037 impl From<ChildStdin> for Stdio {
1038 /// Converts a `ChildStdin` into a `Stdio`
1042 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1045 /// use std::process::{Command, Stdio};
1047 /// let reverse = Command::new("rev")
1048 /// .stdin(Stdio::piped())
1050 /// .expect("failed reverse command");
1052 /// let _echo = Command::new("echo")
1053 /// .arg("Hello, world!")
1054 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1056 /// .expect("failed echo command");
1058 /// // "!dlrow ,olleH" echoed to console
1060 fn from(child: ChildStdin) -> Stdio {
1061 Stdio::from_inner(child.into_inner().into())
1065 #[stable(feature = "stdio_from", since = "1.20.0")]
1066 impl From<ChildStdout> for Stdio {
1067 /// Converts a `ChildStdout` into a `Stdio`
1071 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1074 /// use std::process::{Command, Stdio};
1076 /// let hello = Command::new("echo")
1077 /// .arg("Hello, world!")
1078 /// .stdout(Stdio::piped())
1080 /// .expect("failed echo command");
1082 /// let reverse = Command::new("rev")
1083 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1085 /// .expect("failed reverse command");
1087 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1089 fn from(child: ChildStdout) -> Stdio {
1090 Stdio::from_inner(child.into_inner().into())
1094 #[stable(feature = "stdio_from", since = "1.20.0")]
1095 impl From<ChildStderr> for Stdio {
1096 /// Converts a `ChildStderr` into a `Stdio`
1101 /// use std::process::{Command, Stdio};
1103 /// let reverse = Command::new("rev")
1104 /// .arg("non_existing_file.txt")
1105 /// .stderr(Stdio::piped())
1107 /// .expect("failed reverse command");
1109 /// let cat = Command::new("cat")
1111 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1113 /// .expect("failed echo command");
1116 /// String::from_utf8_lossy(&cat.stdout),
1117 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1120 fn from(child: ChildStderr) -> Stdio {
1121 Stdio::from_inner(child.into_inner().into())
1125 #[stable(feature = "stdio_from", since = "1.20.0")]
1126 impl From<fs::File> for Stdio {
1127 /// Converts a `File` into a `Stdio`
1131 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1134 /// use std::fs::File;
1135 /// use std::process::Command;
1137 /// // With the `foo.txt` file containing `Hello, world!"
1138 /// let file = File::open("foo.txt").unwrap();
1140 /// let reverse = Command::new("rev")
1141 /// .stdin(file) // Implicit File conversion into a Stdio
1143 /// .expect("failed reverse command");
1145 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1147 fn from(file: fs::File) -> Stdio {
1148 Stdio::from_inner(file.into_inner().into())
1152 /// Describes the result of a process after it has terminated.
1154 /// This `struct` is used to represent the exit status of a child process.
1155 /// Child processes are created via the [`Command`] struct and their exit
1156 /// status is exposed through the [`status`] method.
1158 /// [`Command`]: struct.Command.html
1159 /// [`status`]: struct.Command.html#method.status
1160 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1161 #[stable(feature = "process", since = "1.0.0")]
1162 pub struct ExitStatus(imp::ExitStatus);
1165 /// Was termination successful? Signal termination is not considered a
1166 /// success, and success is defined as a zero exit status.
1171 /// use std::process::Command;
1173 /// let status = Command::new("mkdir")
1174 /// .arg("projects")
1176 /// .expect("failed to execute mkdir");
1178 /// if status.success() {
1179 /// println!("'projects/' directory created");
1181 /// println!("failed to create 'projects/' directory");
1184 #[stable(feature = "process", since = "1.0.0")]
1185 pub fn success(&self) -> bool {
1189 /// Returns the exit code of the process, if any.
1191 /// On Unix, this will return `None` if the process was terminated
1192 /// by a signal; `std::os::unix` provides an extension trait for
1193 /// extracting the signal and other details from the `ExitStatus`.
1198 /// use std::process::Command;
1200 /// let status = Command::new("mkdir")
1201 /// .arg("projects")
1203 /// .expect("failed to execute mkdir");
1205 /// match status.code() {
1206 /// Some(code) => println!("Exited with status code: {}", code),
1207 /// None => println!("Process terminated by signal")
1210 #[stable(feature = "process", since = "1.0.0")]
1211 pub fn code(&self) -> Option<i32> {
1216 impl AsInner<imp::ExitStatus> for ExitStatus {
1217 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
1220 impl FromInner<imp::ExitStatus> for ExitStatus {
1221 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1226 #[stable(feature = "process", since = "1.0.0")]
1227 impl fmt::Display for ExitStatus {
1228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1233 /// This type represents the status code a process can return to its
1234 /// parent under normal termination.
1236 /// Numeric values used in this type don't have portable meanings, and
1237 /// different platforms may mask different amounts of them.
1239 /// For the platform's canonical successful and unsuccessful codes, see
1240 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1242 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1243 /// [`FAILURE`]: #associatedconstant.FAILURE
1245 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1246 /// it was ultimately cut from that RFC, and thus this type is more subject
1247 /// to change even than the usual unstable item churn.
1249 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1250 #[derive(Clone, Copy, Debug)]
1251 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1252 pub struct ExitCode(imp::ExitCode);
1254 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1256 /// The canonical ExitCode for successful termination on this platform.
1258 /// Note that a `()`-returning `main` implicitly results in a successful
1259 /// termination, so there's no need to return this from `main` unless
1260 /// you're also returning other possible codes.
1261 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1262 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1264 /// The canonical ExitCode for unsuccessful termination on this platform.
1266 /// If you're only returning this and `SUCCESS` from `main`, consider
1267 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1268 /// return the same codes (but will also `eprintln!` the error).
1269 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1270 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1274 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1275 /// error is returned.
1277 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1278 /// especially the [`Other`] kind might change to more specific kinds in the future.
1280 /// This is equivalent to sending a SIGKILL on Unix platforms.
1287 /// use std::process::Command;
1289 /// let mut command = Command::new("yes");
1290 /// if let Ok(mut child) = command.spawn() {
1291 /// child.kill().expect("command wasn't running");
1293 /// println!("yes command didn't start");
1297 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1298 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1299 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1300 #[stable(feature = "process", since = "1.0.0")]
1301 pub fn kill(&mut self) -> io::Result<()> {
1305 /// Returns the OS-assigned process identifier associated with this child.
1312 /// use std::process::Command;
1314 /// let mut command = Command::new("ls");
1315 /// if let Ok(child) = command.spawn() {
1316 /// println!("Child's ID is {}", child.id());
1318 /// println!("ls command didn't start");
1321 #[stable(feature = "process_id", since = "1.3.0")]
1322 pub fn id(&self) -> u32 {
1326 /// Waits for the child to exit completely, returning the status that it
1327 /// exited with. This function will continue to have the same return value
1328 /// after it has been called at least once.
1330 /// The stdin handle to the child process, if any, will be closed
1331 /// before waiting. This helps avoid deadlock: it ensures that the
1332 /// child does not block waiting for input from the parent, while
1333 /// the parent waits for the child to exit.
1340 /// use std::process::Command;
1342 /// let mut command = Command::new("ls");
1343 /// if let Ok(mut child) = command.spawn() {
1344 /// child.wait().expect("command wasn't running");
1345 /// println!("Child has finished its execution!");
1347 /// println!("ls command didn't start");
1350 #[stable(feature = "process", since = "1.0.0")]
1351 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1352 drop(self.stdin.take());
1353 self.handle.wait().map(ExitStatus)
1356 /// Attempts to collect the exit status of the child if it has already
1359 /// This function will not block the calling thread and will only
1360 /// check to see if the child process has exited or not. If the child has
1361 /// exited then on Unix the process ID is reaped. This function is
1362 /// guaranteed to repeatedly return a successful exit status so long as the
1363 /// child has already exited.
1365 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1366 /// exit status is not available at this time then `Ok(None)` is returned.
1367 /// If an error occurs, then that error is returned.
1369 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1376 /// use std::process::Command;
1378 /// let mut child = Command::new("ls").spawn().unwrap();
1380 /// match child.try_wait() {
1381 /// Ok(Some(status)) => println!("exited with: {}", status),
1383 /// println!("status not ready yet, let's really wait");
1384 /// let res = child.wait();
1385 /// println!("result: {:?}", res);
1387 /// Err(e) => println!("error attempting to wait: {}", e),
1390 #[stable(feature = "process_try_wait", since = "1.18.0")]
1391 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1392 Ok(self.handle.try_wait()?.map(ExitStatus))
1395 /// Simultaneously waits for the child to exit and collect all remaining
1396 /// output on the stdout/stderr handles, returning an `Output`
1399 /// The stdin handle to the child process, if any, will be closed
1400 /// before waiting. This helps avoid deadlock: it ensures that the
1401 /// child does not block waiting for input from the parent, while
1402 /// the parent waits for the child to exit.
1404 /// By default, stdin, stdout and stderr are inherited from the parent.
1405 /// In order to capture the output into this `Result<Output>` it is
1406 /// necessary to create new pipes between parent and child. Use
1407 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1412 /// use std::process::{Command, Stdio};
1414 /// let child = Command::new("/bin/cat")
1415 /// .arg("file.txt")
1416 /// .stdout(Stdio::piped())
1418 /// .expect("failed to execute child");
1420 /// let output = child
1421 /// .wait_with_output()
1422 /// .expect("failed to wait on child");
1424 /// assert!(output.status.success());
1427 #[stable(feature = "process", since = "1.0.0")]
1428 pub fn wait_with_output(mut self) -> io::Result<Output> {
1429 drop(self.stdin.take());
1431 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1432 match (self.stdout.take(), self.stderr.take()) {
1434 (Some(mut out), None) => {
1435 let res = out.read_to_end(&mut stdout);
1438 (None, Some(mut err)) => {
1439 let res = err.read_to_end(&mut stderr);
1442 (Some(out), Some(err)) => {
1443 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1448 let status = self.wait()?;
1457 /// Terminates the current process with the specified exit code.
1459 /// This function will never return and will immediately terminate the current
1460 /// process. The exit code is passed through to the underlying OS and will be
1461 /// available for consumption by another process.
1463 /// Note that because this function never returns, and that it terminates the
1464 /// process, no destructors on the current stack or any other thread's stack
1465 /// will be run. If a clean shutdown is needed it is recommended to only call
1466 /// this function at a known point where there are no more destructors left
1469 /// ## Platform-specific behavior
1471 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1472 /// will be visible to a parent process inspecting the exit code. On most
1473 /// Unix-like platforms, only the eight least-significant bits are considered.
1477 /// Due to this function’s behavior regarding destructors, a conventional way
1478 /// to use the function is to extract the actual computation to another
1479 /// function and compute the exit code from its return value:
1482 /// fn run_app() -> Result<(), ()> {
1483 /// // Application logic here
1488 /// ::std::process::exit(match run_app() {
1491 /// eprintln!("error: {:?}", err);
1498 /// Due to [platform-specific behavior], the exit code for this example will be
1499 /// `0` on Linux, but `256` on Windows:
1502 /// use std::process;
1504 /// process::exit(0x0100);
1507 /// [platform-specific behavior]: #platform-specific-behavior
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 pub fn exit(code: i32) -> ! {
1510 crate::sys_common::cleanup();
1511 crate::sys::os::exit(code)
1514 /// Terminates the process in an abnormal fashion.
1516 /// The function will never return and will immediately terminate the current
1517 /// process in a platform specific "abnormal" manner.
1519 /// Note that because this function never returns, and that it terminates the
1520 /// process, no destructors on the current stack or any other thread's stack
1523 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1524 /// the current thread's stack and calls all destructors.
1525 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1526 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1527 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1529 /// If a clean shutdown is needed it is recommended to only call
1530 /// this function at a known point where there are no more destructors left
1536 /// use std::process;
1539 /// println!("aborting");
1541 /// process::abort();
1543 /// // execution never gets here
1547 /// The `abort` function terminates the process, so the destructor will not
1548 /// get run on the example below:
1551 /// use std::process;
1555 /// impl Drop for HasDrop {
1556 /// fn drop(&mut self) {
1557 /// println!("This will never be printed!");
1562 /// let _x = HasDrop;
1563 /// process::abort();
1564 /// // the destructor implemented for HasDrop will never get run
1568 /// [`panic!`]: ../../std/macro.panic.html
1569 /// [panic hook]: ../../std/panic/fn.set_hook.html
1570 #[stable(feature = "process_abort", since = "1.17.0")]
1571 pub fn abort() -> ! {
1572 unsafe { crate::sys::abort_internal() };
1575 /// Returns the OS-assigned process identifier associated with this process.
1582 /// use std::process;
1584 /// println!("My pid is {}", process::id());
1588 #[stable(feature = "getpid", since = "1.26.0")]
1589 pub fn id() -> u32 {
1590 crate::sys::os::getpid()
1593 /// A trait for implementing arbitrary return types in the `main` function.
1595 /// The c-main function only supports to return integers as return type.
1596 /// So, every type implementing the `Termination` trait has to be converted
1599 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1600 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1601 #[cfg_attr(not(test), lang = "termination")]
1602 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1603 #[rustc_on_unimplemented(
1604 message="`main` has invalid return type `{Self}`",
1605 label="`main` can only return types that implement `{Termination}`")]
1606 pub trait Termination {
1607 /// Is called to get the representation of the value as status code.
1608 /// This status code is returned to the operating system.
1609 fn report(self) -> i32;
1612 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1613 impl Termination for () {
1615 fn report(self) -> i32 { ExitCode::SUCCESS.report() }
1618 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1619 impl<E: fmt::Debug> Termination for Result<(), E> {
1620 fn report(self) -> i32 {
1622 Ok(()) => ().report(),
1623 Err(err) => Err::<!, _>(err).report(),
1628 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1629 impl Termination for ! {
1630 fn report(self) -> i32 { self }
1633 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1634 impl<E: fmt::Debug> Termination for Result<!, E> {
1635 fn report(self) -> i32 {
1636 let Err(err) = self;
1637 eprintln!("Error: {:?}", err);
1638 ExitCode::FAILURE.report()
1642 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1643 impl Termination for ExitCode {
1645 fn report(self) -> i32 {
1650 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
1652 use crate::io::prelude::*;
1654 use crate::io::ErrorKind;
1656 use super::{Command, Output, Stdio};
1658 // FIXME(#10380) these tests should not all be ignored on android.
1661 #[cfg_attr(target_os = "android", ignore)]
1663 let p = if cfg!(target_os = "windows") {
1664 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1666 Command::new("true").spawn()
1669 let mut p = p.unwrap();
1670 assert!(p.wait().unwrap().success());
1674 #[cfg_attr(target_os = "android", ignore)]
1675 fn smoke_failure() {
1676 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1683 #[cfg_attr(target_os = "android", ignore)]
1684 fn exit_reported_right() {
1685 let p = if cfg!(target_os = "windows") {
1686 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1688 Command::new("false").spawn()
1691 let mut p = p.unwrap();
1692 assert!(p.wait().unwrap().code() == Some(1));
1698 #[cfg_attr(target_os = "android", ignore)]
1699 fn signal_reported_right() {
1700 use crate::os::unix::process::ExitStatusExt;
1702 let mut p = Command::new("/bin/sh")
1703 .arg("-c").arg("read a")
1704 .stdin(Stdio::piped())
1707 match p.wait().unwrap().signal() {
1709 result => panic!("not terminated by signal 9 (instead, {:?})",
1714 pub fn run_output(mut cmd: Command) -> String {
1715 let p = cmd.spawn();
1717 let mut p = p.unwrap();
1718 assert!(p.stdout.is_some());
1719 let mut ret = String::new();
1720 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1721 assert!(p.wait().unwrap().success());
1726 #[cfg_attr(target_os = "android", ignore)]
1728 if cfg!(target_os = "windows") {
1729 let mut cmd = Command::new("cmd");
1730 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1731 assert_eq!(run_output(cmd), "foobar\r\n");
1733 let mut cmd = Command::new("echo");
1734 cmd.arg("foobar").stdout(Stdio::piped());
1735 assert_eq!(run_output(cmd), "foobar\n");
1740 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1741 fn set_current_dir_works() {
1742 let mut cmd = Command::new("/bin/sh");
1743 cmd.arg("-c").arg("pwd")
1745 .stdout(Stdio::piped());
1746 assert_eq!(run_output(cmd), "/\n");
1750 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1752 let mut p = Command::new("/bin/sh")
1753 .arg("-c").arg("read line; echo $line")
1754 .stdin(Stdio::piped())
1755 .stdout(Stdio::piped())
1757 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1758 drop(p.stdin.take());
1759 let mut out = String::new();
1760 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1761 assert!(p.wait().unwrap().success());
1762 assert_eq!(out, "foobar\n");
1767 #[cfg_attr(target_os = "android", ignore)]
1770 use crate::os::unix::prelude::*;
1772 let mut p = Command::new("/bin/sh")
1773 .arg("-c").arg("true")
1774 .uid(unsafe { libc::getuid() })
1775 .gid(unsafe { libc::getgid() })
1777 assert!(p.wait().unwrap().success());
1781 #[cfg_attr(target_os = "android", ignore)]
1783 fn uid_to_root_fails() {
1784 use crate::os::unix::prelude::*;
1786 // if we're already root, this isn't a valid test. Most of the bots run
1787 // as non-root though (android is an exception).
1788 if unsafe { libc::getuid() == 0 } { return }
1789 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1793 #[cfg_attr(target_os = "android", ignore)]
1794 fn test_process_status() {
1795 let mut status = if cfg!(target_os = "windows") {
1796 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1798 Command::new("false").status().unwrap()
1800 assert!(status.code() == Some(1));
1802 status = if cfg!(target_os = "windows") {
1803 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1805 Command::new("true").status().unwrap()
1807 assert!(status.success());
1811 fn test_process_output_fail_to_start() {
1812 match Command::new("/no-binary-by-this-name-should-exist").output() {
1813 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1819 #[cfg_attr(target_os = "android", ignore)]
1820 fn test_process_output_output() {
1821 let Output {status, stdout, stderr}
1822 = if cfg!(target_os = "windows") {
1823 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1825 Command::new("echo").arg("hello").output().unwrap()
1827 let output_str = str::from_utf8(&stdout).unwrap();
1829 assert!(status.success());
1830 assert_eq!(output_str.trim().to_string(), "hello");
1831 assert_eq!(stderr, Vec::new());
1835 #[cfg_attr(target_os = "android", ignore)]
1836 fn test_process_output_error() {
1837 let Output {status, stdout, stderr}
1838 = if cfg!(target_os = "windows") {
1839 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1841 Command::new("mkdir").arg("./").output().unwrap()
1844 assert!(status.code() == Some(1));
1845 assert_eq!(stdout, Vec::new());
1846 assert!(!stderr.is_empty());
1850 #[cfg_attr(target_os = "android", ignore)]
1851 fn test_finish_once() {
1852 let mut prog = if cfg!(target_os = "windows") {
1853 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1855 Command::new("false").spawn().unwrap()
1857 assert!(prog.wait().unwrap().code() == Some(1));
1861 #[cfg_attr(target_os = "android", ignore)]
1862 fn test_finish_twice() {
1863 let mut prog = if cfg!(target_os = "windows") {
1864 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1866 Command::new("false").spawn().unwrap()
1868 assert!(prog.wait().unwrap().code() == Some(1));
1869 assert!(prog.wait().unwrap().code() == Some(1));
1873 #[cfg_attr(target_os = "android", ignore)]
1874 fn test_wait_with_output_once() {
1875 let prog = if cfg!(target_os = "windows") {
1876 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1878 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1881 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1882 let output_str = str::from_utf8(&stdout).unwrap();
1884 assert!(status.success());
1885 assert_eq!(output_str.trim().to_string(), "hello");
1886 assert_eq!(stderr, Vec::new());
1889 #[cfg(all(unix, not(target_os="android")))]
1890 pub fn env_cmd() -> Command {
1893 #[cfg(target_os="android")]
1894 pub fn env_cmd() -> Command {
1895 let mut cmd = Command::new("/system/bin/sh");
1896 cmd.arg("-c").arg("set");
1901 pub fn env_cmd() -> Command {
1902 let mut cmd = Command::new("cmd");
1903 cmd.arg("/c").arg("set");
1908 fn test_override_env() {
1911 // In some build environments (such as chrooted Nix builds), `env` can
1912 // only be found in the explicitly-provided PATH env variable, not in
1913 // default places such as /bin or /usr/bin. So we need to pass through
1914 // PATH to our sub-process.
1915 let mut cmd = env_cmd();
1916 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1917 if let Some(p) = env::var_os("PATH") {
1918 cmd.env("PATH", &p);
1920 let result = cmd.output().unwrap();
1921 let output = String::from_utf8_lossy(&result.stdout).to_string();
1923 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1924 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1928 fn test_add_to_env() {
1929 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1930 let output = String::from_utf8_lossy(&result.stdout).to_string();
1932 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1933 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1937 fn test_capture_env_at_spawn() {
1940 let mut cmd = env_cmd();
1941 cmd.env("RUN_TEST_NEW_ENV1", "123");
1943 // This variable will not be present if the environment has already
1944 // been captured above.
1945 env::set_var("RUN_TEST_NEW_ENV2", "456");
1946 let result = cmd.output().unwrap();
1947 env::remove_var("RUN_TEST_NEW_ENV2");
1949 let output = String::from_utf8_lossy(&result.stdout).to_string();
1951 assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1952 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1953 assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1954 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1957 // Regression tests for #30858.
1959 fn test_interior_nul_in_progname_is_error() {
1960 match Command::new("has-some-\0\0s-inside").spawn() {
1961 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1967 fn test_interior_nul_in_arg_is_error() {
1968 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1969 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1975 fn test_interior_nul_in_args_is_error() {
1976 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1977 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1983 fn test_interior_nul_in_current_dir_is_error() {
1984 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1985 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1990 // Regression tests for #30862.
1992 fn test_interior_nul_in_env_key_is_error() {
1993 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1994 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2000 fn test_interior_nul_in_env_value_is_error() {
2001 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
2002 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
2007 /// Tests that process creation flags work by debugging a process.
2008 /// Other creation flags make it hard or impossible to detect
2009 /// behavioral changes in the process.
2012 fn test_creation_flags() {
2013 use crate::os::windows::process::CommandExt;
2014 use crate::sys::c::{BOOL, DWORD, INFINITE};
2016 struct DEBUG_EVENT {
2017 pub event_code: DWORD,
2018 pub process_id: DWORD,
2019 pub thread_id: DWORD,
2020 // This is a union in the real struct, but we don't
2021 // need this data for the purposes of this test.
2022 pub _junk: [u8; 164],
2026 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
2027 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
2028 dwContinueStatus: DWORD) -> BOOL;
2031 const DEBUG_PROCESS: DWORD = 1;
2032 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
2033 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
2035 let mut child = Command::new("cmd")
2036 .creation_flags(DEBUG_PROCESS)
2037 .stdin(Stdio::piped()).spawn().unwrap();
2038 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
2040 let mut event = DEBUG_EVENT {
2047 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
2048 panic!("WaitForDebugEvent failed!");
2052 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
2056 if unsafe { ContinueDebugEvent(event.process_id,
2058 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
2059 panic!("ContinueDebugEvent failed!");
2062 assert!(events > 0);
2066 fn test_command_implements_send() {
2067 fn take_send_type<T: Send>(_: T) {}
2068 take_send_type(Command::new(""))