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 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");
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, or the [`wait`] method
1157 /// of a [`Child`] process.
1159 /// [`Command`]: struct.Command.html
1160 /// [`Child`]: struct.Child.html
1161 /// [`status`]: struct.Command.html#method.status
1162 /// [`wait`]: struct.Child.html#method.wait
1163 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1164 #[stable(feature = "process", since = "1.0.0")]
1165 pub struct ExitStatus(imp::ExitStatus);
1168 /// Was termination successful? Signal termination is not considered a
1169 /// success, and success is defined as a zero exit status.
1174 /// use std::process::Command;
1176 /// let status = Command::new("mkdir")
1177 /// .arg("projects")
1179 /// .expect("failed to execute mkdir");
1181 /// if status.success() {
1182 /// println!("'projects/' directory created");
1184 /// println!("failed to create 'projects/' directory");
1187 #[stable(feature = "process", since = "1.0.0")]
1188 pub fn success(&self) -> bool {
1192 /// Returns the exit code of the process, if any.
1194 /// On Unix, this will return `None` if the process was terminated
1195 /// by a signal; `std::os::unix` provides an extension trait for
1196 /// extracting the signal and other details from the `ExitStatus`.
1201 /// use std::process::Command;
1203 /// let status = Command::new("mkdir")
1204 /// .arg("projects")
1206 /// .expect("failed to execute mkdir");
1208 /// match status.code() {
1209 /// Some(code) => println!("Exited with status code: {}", code),
1210 /// None => println!("Process terminated by signal")
1213 #[stable(feature = "process", since = "1.0.0")]
1214 pub fn code(&self) -> Option<i32> {
1219 impl AsInner<imp::ExitStatus> for ExitStatus {
1220 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
1223 impl FromInner<imp::ExitStatus> for ExitStatus {
1224 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1229 #[stable(feature = "process", since = "1.0.0")]
1230 impl fmt::Display for ExitStatus {
1231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236 /// This type represents the status code a process can return to its
1237 /// parent under normal termination.
1239 /// Numeric values used in this type don't have portable meanings, and
1240 /// different platforms may mask different amounts of them.
1242 /// For the platform's canonical successful and unsuccessful codes, see
1243 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1245 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1246 /// [`FAILURE`]: #associatedconstant.FAILURE
1248 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1249 /// it was ultimately cut from that RFC, and thus this type is more subject
1250 /// to change even than the usual unstable item churn.
1252 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1253 #[derive(Clone, Copy, Debug)]
1254 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1255 pub struct ExitCode(imp::ExitCode);
1257 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1259 /// The canonical ExitCode for successful termination on this platform.
1261 /// Note that a `()`-returning `main` implicitly results in a successful
1262 /// termination, so there's no need to return this from `main` unless
1263 /// you're also returning other possible codes.
1264 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1265 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1267 /// The canonical ExitCode for unsuccessful termination on this platform.
1269 /// If you're only returning this and `SUCCESS` from `main`, consider
1270 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1271 /// return the same codes (but will also `eprintln!` the error).
1272 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1273 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1277 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1278 /// error is returned.
1280 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1281 /// especially the [`Other`] kind might change to more specific kinds in the future.
1283 /// This is equivalent to sending a SIGKILL on Unix platforms.
1290 /// use std::process::Command;
1292 /// let mut command = Command::new("yes");
1293 /// if let Ok(mut child) = command.spawn() {
1294 /// child.kill().expect("command wasn't running");
1296 /// println!("yes command didn't start");
1300 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1301 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1302 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1303 #[stable(feature = "process", since = "1.0.0")]
1304 pub fn kill(&mut self) -> io::Result<()> {
1308 /// Returns the OS-assigned process identifier associated with this child.
1315 /// use std::process::Command;
1317 /// let mut command = Command::new("ls");
1318 /// if let Ok(child) = command.spawn() {
1319 /// println!("Child's ID is {}", child.id());
1321 /// println!("ls command didn't start");
1324 #[stable(feature = "process_id", since = "1.3.0")]
1325 pub fn id(&self) -> u32 {
1329 /// Waits for the child to exit completely, returning the status that it
1330 /// exited with. This function will continue to have the same return value
1331 /// after it has been called at least once.
1333 /// The stdin handle to the child process, if any, will be closed
1334 /// before waiting. This helps avoid deadlock: it ensures that the
1335 /// child does not block waiting for input from the parent, while
1336 /// the parent waits for the child to exit.
1343 /// use std::process::Command;
1345 /// let mut command = Command::new("ls");
1346 /// if let Ok(mut child) = command.spawn() {
1347 /// child.wait().expect("command wasn't running");
1348 /// println!("Child has finished its execution!");
1350 /// println!("ls command didn't start");
1353 #[stable(feature = "process", since = "1.0.0")]
1354 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1355 drop(self.stdin.take());
1356 self.handle.wait().map(ExitStatus)
1359 /// Attempts to collect the exit status of the child if it has already
1362 /// This function will not block the calling thread and will only
1363 /// check to see if the child process has exited or not. If the child has
1364 /// exited then on Unix the process ID is reaped. This function is
1365 /// guaranteed to repeatedly return a successful exit status so long as the
1366 /// child has already exited.
1368 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1369 /// exit status is not available at this time then `Ok(None)` is returned.
1370 /// If an error occurs, then that error is returned.
1372 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1379 /// use std::process::Command;
1381 /// let mut child = Command::new("ls").spawn().unwrap();
1383 /// match child.try_wait() {
1384 /// Ok(Some(status)) => println!("exited with: {}", status),
1386 /// println!("status not ready yet, let's really wait");
1387 /// let res = child.wait();
1388 /// println!("result: {:?}", res);
1390 /// Err(e) => println!("error attempting to wait: {}", e),
1393 #[stable(feature = "process_try_wait", since = "1.18.0")]
1394 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1395 Ok(self.handle.try_wait()?.map(ExitStatus))
1398 /// Simultaneously waits for the child to exit and collect all remaining
1399 /// output on the stdout/stderr handles, returning an `Output`
1402 /// The stdin handle to the child process, if any, will be closed
1403 /// before waiting. This helps avoid deadlock: it ensures that the
1404 /// child does not block waiting for input from the parent, while
1405 /// the parent waits for the child to exit.
1407 /// By default, stdin, stdout and stderr are inherited from the parent.
1408 /// In order to capture the output into this `Result<Output>` it is
1409 /// necessary to create new pipes between parent and child. Use
1410 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1415 /// use std::process::{Command, Stdio};
1417 /// let child = Command::new("/bin/cat")
1418 /// .arg("file.txt")
1419 /// .stdout(Stdio::piped())
1421 /// .expect("failed to execute child");
1423 /// let output = child
1424 /// .wait_with_output()
1425 /// .expect("failed to wait on child");
1427 /// assert!(output.status.success());
1430 #[stable(feature = "process", since = "1.0.0")]
1431 pub fn wait_with_output(mut self) -> io::Result<Output> {
1432 drop(self.stdin.take());
1434 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1435 match (self.stdout.take(), self.stderr.take()) {
1437 (Some(mut out), None) => {
1438 let res = out.read_to_end(&mut stdout);
1441 (None, Some(mut err)) => {
1442 let res = err.read_to_end(&mut stderr);
1445 (Some(out), Some(err)) => {
1446 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1451 let status = self.wait()?;
1460 /// Terminates the current process with the specified exit code.
1462 /// This function will never return and will immediately terminate the current
1463 /// process. The exit code is passed through to the underlying OS and will be
1464 /// available for consumption by another process.
1466 /// Note that because this function never returns, and that it terminates the
1467 /// process, no destructors on the current stack or any other thread's stack
1468 /// will be run. If a clean shutdown is needed it is recommended to only call
1469 /// this function at a known point where there are no more destructors left
1472 /// ## Platform-specific behavior
1474 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1475 /// will be visible to a parent process inspecting the exit code. On most
1476 /// Unix-like platforms, only the eight least-significant bits are considered.
1480 /// Due to this function’s behavior regarding destructors, a conventional way
1481 /// to use the function is to extract the actual computation to another
1482 /// function and compute the exit code from its return value:
1485 /// fn run_app() -> Result<(), ()> {
1486 /// // Application logic here
1491 /// std::process::exit(match run_app() {
1494 /// eprintln!("error: {:?}", err);
1501 /// Due to [platform-specific behavior], the exit code for this example will be
1502 /// `0` on Linux, but `256` on Windows:
1505 /// use std::process;
1507 /// process::exit(0x0100);
1510 /// [platform-specific behavior]: #platform-specific-behavior
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 pub fn exit(code: i32) -> ! {
1513 crate::sys_common::cleanup();
1514 crate::sys::os::exit(code)
1517 /// Terminates the process in an abnormal fashion.
1519 /// The function will never return and will immediately terminate the current
1520 /// process in a platform specific "abnormal" manner.
1522 /// Note that because this function never returns, and that it terminates the
1523 /// process, no destructors on the current stack or any other thread's stack
1526 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1527 /// the current thread's stack and calls all destructors.
1528 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1529 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1530 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1532 /// If a clean shutdown is needed it is recommended to only call
1533 /// this function at a known point where there are no more destructors left
1539 /// use std::process;
1542 /// println!("aborting");
1544 /// process::abort();
1546 /// // execution never gets here
1550 /// The `abort` function terminates the process, so the destructor will not
1551 /// get run on the example below:
1554 /// use std::process;
1558 /// impl Drop for HasDrop {
1559 /// fn drop(&mut self) {
1560 /// println!("This will never be printed!");
1565 /// let _x = HasDrop;
1566 /// process::abort();
1567 /// // the destructor implemented for HasDrop will never get run
1571 /// [`panic!`]: ../../std/macro.panic.html
1572 /// [panic hook]: ../../std/panic/fn.set_hook.html
1573 #[stable(feature = "process_abort", since = "1.17.0")]
1574 pub fn abort() -> ! {
1575 unsafe { crate::sys::abort_internal() };
1578 /// Returns the OS-assigned process identifier associated with this process.
1585 /// use std::process;
1587 /// println!("My pid is {}", process::id());
1591 #[stable(feature = "getpid", since = "1.26.0")]
1592 pub fn id() -> u32 {
1593 crate::sys::os::getpid()
1596 /// A trait for implementing arbitrary return types in the `main` function.
1598 /// The C-main function only supports to return integers as return type.
1599 /// So, every type implementing the `Termination` trait has to be converted
1602 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1603 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1604 #[cfg_attr(not(test), lang = "termination")]
1605 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1606 #[rustc_on_unimplemented(
1607 message="`main` has invalid return type `{Self}`",
1608 label="`main` can only return types that implement `{Termination}`")]
1609 pub trait Termination {
1610 /// Is called to get the representation of the value as status code.
1611 /// This status code is returned to the operating system.
1612 fn report(self) -> i32;
1615 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1616 impl Termination for () {
1618 fn report(self) -> i32 { ExitCode::SUCCESS.report() }
1621 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1622 impl<E: fmt::Debug> Termination for Result<(), E> {
1623 fn report(self) -> i32 {
1625 Ok(()) => ().report(),
1626 Err(err) => Err::<!, _>(err).report(),
1631 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1632 impl Termination for ! {
1633 fn report(self) -> i32 { self }
1636 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1637 impl<E: fmt::Debug> Termination for Result<!, E> {
1638 fn report(self) -> i32 {
1639 let Err(err) = self;
1640 eprintln!("Error: {:?}", err);
1641 ExitCode::FAILURE.report()
1645 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1646 impl Termination for ExitCode {
1648 fn report(self) -> i32 {
1653 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
1655 use crate::io::prelude::*;
1657 use crate::io::ErrorKind;
1659 use super::{Command, Output, Stdio};
1661 // FIXME(#10380) these tests should not all be ignored on android.
1664 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1666 let p = if cfg!(target_os = "windows") {
1667 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1669 Command::new("true").spawn()
1672 let mut p = p.unwrap();
1673 assert!(p.wait().unwrap().success());
1677 #[cfg_attr(target_os = "android", ignore)]
1678 fn smoke_failure() {
1679 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1686 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1687 fn exit_reported_right() {
1688 let p = if cfg!(target_os = "windows") {
1689 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1691 Command::new("false").spawn()
1694 let mut p = p.unwrap();
1695 assert!(p.wait().unwrap().code() == Some(1));
1701 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1702 fn signal_reported_right() {
1703 use crate::os::unix::process::ExitStatusExt;
1705 let mut p = Command::new("/bin/sh")
1706 .arg("-c").arg("read a")
1707 .stdin(Stdio::piped())
1710 match p.wait().unwrap().signal() {
1712 result => panic!("not terminated by signal 9 (instead, {:?})",
1717 pub fn run_output(mut cmd: Command) -> String {
1718 let p = cmd.spawn();
1720 let mut p = p.unwrap();
1721 assert!(p.stdout.is_some());
1722 let mut ret = String::new();
1723 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1724 assert!(p.wait().unwrap().success());
1729 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1731 if cfg!(target_os = "windows") {
1732 let mut cmd = Command::new("cmd");
1733 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1734 assert_eq!(run_output(cmd), "foobar\r\n");
1736 let mut cmd = Command::new("echo");
1737 cmd.arg("foobar").stdout(Stdio::piped());
1738 assert_eq!(run_output(cmd), "foobar\n");
1743 #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
1744 fn set_current_dir_works() {
1745 let mut cmd = Command::new("/bin/sh");
1746 cmd.arg("-c").arg("pwd")
1748 .stdout(Stdio::piped());
1749 assert_eq!(run_output(cmd), "/\n");
1753 #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
1755 let mut p = Command::new("/bin/sh")
1756 .arg("-c").arg("read line; echo $line")
1757 .stdin(Stdio::piped())
1758 .stdout(Stdio::piped())
1760 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1761 drop(p.stdin.take());
1762 let mut out = String::new();
1763 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1764 assert!(p.wait().unwrap().success());
1765 assert_eq!(out, "foobar\n");
1769 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1770 fn test_process_status() {
1771 let mut status = if cfg!(target_os = "windows") {
1772 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1774 Command::new("false").status().unwrap()
1776 assert!(status.code() == Some(1));
1778 status = if cfg!(target_os = "windows") {
1779 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1781 Command::new("true").status().unwrap()
1783 assert!(status.success());
1787 fn test_process_output_fail_to_start() {
1788 match Command::new("/no-binary-by-this-name-should-exist").output() {
1789 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1795 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1796 fn test_process_output_output() {
1797 let Output {status, stdout, stderr}
1798 = if cfg!(target_os = "windows") {
1799 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1801 Command::new("echo").arg("hello").output().unwrap()
1803 let output_str = str::from_utf8(&stdout).unwrap();
1805 assert!(status.success());
1806 assert_eq!(output_str.trim().to_string(), "hello");
1807 assert_eq!(stderr, Vec::new());
1811 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1812 fn test_process_output_error() {
1813 let Output {status, stdout, stderr}
1814 = if cfg!(target_os = "windows") {
1815 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1817 Command::new("mkdir").arg("./").output().unwrap()
1820 assert!(status.code() == Some(1));
1821 assert_eq!(stdout, Vec::new());
1822 assert!(!stderr.is_empty());
1826 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1827 fn test_finish_once() {
1828 let mut prog = if cfg!(target_os = "windows") {
1829 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1831 Command::new("false").spawn().unwrap()
1833 assert!(prog.wait().unwrap().code() == Some(1));
1837 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1838 fn test_finish_twice() {
1839 let mut prog = if cfg!(target_os = "windows") {
1840 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1842 Command::new("false").spawn().unwrap()
1844 assert!(prog.wait().unwrap().code() == Some(1));
1845 assert!(prog.wait().unwrap().code() == Some(1));
1849 #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
1850 fn test_wait_with_output_once() {
1851 let prog = if cfg!(target_os = "windows") {
1852 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1854 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1857 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1858 let output_str = str::from_utf8(&stdout).unwrap();
1860 assert!(status.success());
1861 assert_eq!(output_str.trim().to_string(), "hello");
1862 assert_eq!(stderr, Vec::new());
1865 #[cfg(all(unix, not(target_os="android")))]
1866 pub fn env_cmd() -> Command {
1869 #[cfg(target_os="android")]
1870 pub fn env_cmd() -> Command {
1871 let mut cmd = Command::new("/system/bin/sh");
1872 cmd.arg("-c").arg("set");
1877 pub fn env_cmd() -> Command {
1878 let mut cmd = Command::new("cmd");
1879 cmd.arg("/c").arg("set");
1884 #[cfg_attr(target_os = "vxworks", ignore)]
1885 fn test_override_env() {
1888 // In some build environments (such as chrooted Nix builds), `env` can
1889 // only be found in the explicitly-provided PATH env variable, not in
1890 // default places such as /bin or /usr/bin. So we need to pass through
1891 // PATH to our sub-process.
1892 let mut cmd = env_cmd();
1893 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1894 if let Some(p) = env::var_os("PATH") {
1895 cmd.env("PATH", &p);
1897 let result = cmd.output().unwrap();
1898 let output = String::from_utf8_lossy(&result.stdout).to_string();
1900 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1901 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1905 #[cfg_attr(target_os = "vxworks", ignore)]
1906 fn test_add_to_env() {
1907 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1908 let output = String::from_utf8_lossy(&result.stdout).to_string();
1910 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1911 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1915 #[cfg_attr(target_os = "vxworks", ignore)]
1916 fn test_capture_env_at_spawn() {
1919 let mut cmd = env_cmd();
1920 cmd.env("RUN_TEST_NEW_ENV1", "123");
1922 // This variable will not be present if the environment has already
1923 // been captured above.
1924 env::set_var("RUN_TEST_NEW_ENV2", "456");
1925 let result = cmd.output().unwrap();
1926 env::remove_var("RUN_TEST_NEW_ENV2");
1928 let output = String::from_utf8_lossy(&result.stdout).to_string();
1930 assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1931 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1932 assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1933 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1936 // Regression tests for #30858.
1938 fn test_interior_nul_in_progname_is_error() {
1939 match Command::new("has-some-\0\0s-inside").spawn() {
1940 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1946 fn test_interior_nul_in_arg_is_error() {
1947 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1948 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1954 fn test_interior_nul_in_args_is_error() {
1955 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1956 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1962 fn test_interior_nul_in_current_dir_is_error() {
1963 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1964 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1969 // Regression tests for #30862.
1971 #[cfg_attr(target_os = "vxworks", ignore)]
1972 fn test_interior_nul_in_env_key_is_error() {
1973 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1974 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1980 #[cfg_attr(target_os = "vxworks", ignore)]
1981 fn test_interior_nul_in_env_value_is_error() {
1982 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1983 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1988 /// Tests that process creation flags work by debugging a process.
1989 /// Other creation flags make it hard or impossible to detect
1990 /// behavioral changes in the process.
1993 fn test_creation_flags() {
1994 use crate::os::windows::process::CommandExt;
1995 use crate::sys::c::{BOOL, DWORD, INFINITE};
1997 struct DEBUG_EVENT {
1998 pub event_code: DWORD,
1999 pub process_id: DWORD,
2000 pub thread_id: DWORD,
2001 // This is a union in the real struct, but we don't
2002 // need this data for the purposes of this test.
2003 pub _junk: [u8; 164],
2007 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
2008 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
2009 dwContinueStatus: DWORD) -> BOOL;
2012 const DEBUG_PROCESS: DWORD = 1;
2013 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
2014 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
2016 let mut child = Command::new("cmd")
2017 .creation_flags(DEBUG_PROCESS)
2018 .stdin(Stdio::piped()).spawn().unwrap();
2019 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
2021 let mut event = DEBUG_EVENT {
2028 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
2029 panic!("WaitForDebugEvent failed!");
2033 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
2037 if unsafe { ContinueDebugEvent(event.process_id,
2039 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
2040 panic!("ContinueDebugEvent failed!");
2043 assert!(events > 0);
2047 fn test_command_implements_send() {
2048 fn take_send_type<T: Send>(_: T) {}
2049 take_send_type(Command::new(""))