1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A module for working with processes.
13 //! This module is mostly concerned with spawning and interacting with child
14 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
17 //! # Spawning a process
19 //! The [`Command`] struct is used to configure and spawn processes:
22 //! use std::process::Command;
24 //! let output = Command::new("echo")
25 //! .arg("Hello world")
27 //! .expect("Failed to execute command");
29 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
32 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
33 //! to spawn a process. In particular, [`output`] spawns the child process and
34 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
35 //! that represents the spawned child process.
39 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
40 //! configured by passing an [`Stdio`] to the corresponding method on
41 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
42 //! example, piping output from one command into another command can be done
46 //! use std::process::{Command, Stdio};
48 //! // stdout must be configured with `Stdio::piped` in order to use
49 //! // `echo_child.stdout`
50 //! let echo_child = Command::new("echo")
51 //! .arg("Oh no, a tpyo!")
52 //! .stdout(Stdio::piped())
54 //! .expect("Failed to start echo process");
56 //! // Note that `echo_child` is moved here, but we won't be needing
57 //! // `echo_child` anymore
58 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
60 //! let mut sed_child = Command::new("sed")
61 //! .arg("s/tpyo/typo/")
62 //! .stdin(Stdio::from(echo_out))
63 //! .stdout(Stdio::piped())
65 //! .expect("Failed to start sed process");
67 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
68 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
71 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
72 //! [`ChildStdin`] implements [`Write`]:
75 //! use std::process::{Command, Stdio};
76 //! use std::io::Write;
78 //! let mut child = Command::new("/bin/cat")
79 //! .stdin(Stdio::piped())
80 //! .stdout(Stdio::piped())
82 //! .expect("failed to execute child");
85 //! // limited borrow of stdin
86 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
87 //! stdin.write_all(b"test").expect("failed to write to stdin");
90 //! let output = child
91 //! .wait_with_output()
92 //! .expect("failed to wait on child");
94 //! assert_eq!(b"test", output.stdout.as_slice());
97 //! [`abort`]: fn.abort.html
98 //! [`exit`]: fn.exit.html
100 //! [`Command`]: struct.Command.html
101 //! [`spawn`]: struct.Command.html#method.spawn
102 //! [`output`]: struct.Command.html#method.output
104 //! [`Child`]: struct.Child.html
105 //! [`ChildStdin`]: struct.ChildStdin.html
106 //! [`ChildStdout`]: struct.ChildStdout.html
107 //! [`ChildStderr`]: struct.ChildStderr.html
108 //! [`Stdio`]: struct.Stdio.html
110 //! [`stdout`]: struct.Command.html#method.stdout
111 //! [`stdin`]: struct.Command.html#method.stdin
112 //! [`stderr`]: struct.Command.html#method.stderr
114 //! [`Write`]: ../io/trait.Write.html
115 //! [`Read`]: ../io/trait.Read.html
117 #![stable(feature = "process", since = "1.0.0")]
124 use io::{self, Initializer};
127 use sys::pipe::{read2, AnonPipe};
128 use sys::process as imp;
129 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
131 /// Representation of a running or exited child process.
133 /// This structure is used to represent and manage child processes. A child
134 /// process is created via the [`Command`] struct, which configures the
135 /// spawning process and can itself be constructed using a builder-style
138 /// There is no implementation of [`Drop`] for child processes,
139 /// so if you do not ensure the `Child` has exited then it will continue to
140 /// run, even after the `Child` handle to the child process has gone out of
143 /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
144 /// the parent process wait until the child has actually exited before
150 /// use std::process::Command;
152 /// let mut child = Command::new("/bin/cat")
155 /// .expect("failed to execute child");
157 /// let ecode = child.wait()
158 /// .expect("failed to wait on child");
160 /// assert!(ecode.success());
163 /// [`Command`]: struct.Command.html
164 /// [`Drop`]: ../../core/ops/trait.Drop.html
165 /// [`wait`]: #method.wait
166 #[stable(feature = "process", since = "1.0.0")]
168 handle: imp::Process,
170 /// The handle for writing to the child's standard input (stdin), if it has
172 #[stable(feature = "process", since = "1.0.0")]
173 pub stdin: Option<ChildStdin>,
175 /// The handle for reading from the child's standard output (stdout), if it
176 /// has been captured.
177 #[stable(feature = "process", since = "1.0.0")]
178 pub stdout: Option<ChildStdout>,
180 /// The handle for reading from the child's standard error (stderr), if it
181 /// has been captured.
182 #[stable(feature = "process", since = "1.0.0")]
183 pub stderr: Option<ChildStderr>,
186 impl AsInner<imp::Process> for Child {
187 fn as_inner(&self) -> &imp::Process { &self.handle }
190 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
191 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
194 stdin: io.stdin.map(ChildStdin::from_inner),
195 stdout: io.stdout.map(ChildStdout::from_inner),
196 stderr: io.stderr.map(ChildStderr::from_inner),
201 impl IntoInner<imp::Process> for Child {
202 fn into_inner(self) -> imp::Process { self.handle }
205 #[stable(feature = "std_debug", since = "1.16.0")]
206 impl fmt::Debug for Child {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 f.debug_struct("Child")
209 .field("stdin", &self.stdin)
210 .field("stdout", &self.stdout)
211 .field("stderr", &self.stderr)
216 /// A handle to a child process's standard input (stdin).
218 /// This struct is used in the [`stdin`] field on [`Child`].
220 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
221 /// file handle will be closed. If the child process was blocked on input prior
222 /// to being dropped, it will become unblocked after dropping.
224 /// [`Child`]: struct.Child.html
225 /// [`stdin`]: struct.Child.html#structfield.stdin
226 /// [dropped]: ../ops/trait.Drop.html
227 #[stable(feature = "process", since = "1.0.0")]
228 pub struct ChildStdin {
232 #[stable(feature = "process", since = "1.0.0")]
233 impl Write for ChildStdin {
234 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
235 self.inner.write(buf)
238 fn flush(&mut self) -> io::Result<()> {
243 impl AsInner<AnonPipe> for ChildStdin {
244 fn as_inner(&self) -> &AnonPipe { &self.inner }
247 impl IntoInner<AnonPipe> for ChildStdin {
248 fn into_inner(self) -> AnonPipe { self.inner }
251 impl FromInner<AnonPipe> for ChildStdin {
252 fn from_inner(pipe: AnonPipe) -> ChildStdin {
253 ChildStdin { inner: pipe }
257 #[stable(feature = "std_debug", since = "1.16.0")]
258 impl fmt::Debug for ChildStdin {
259 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
260 f.pad("ChildStdin { .. }")
264 /// A handle to a child process's standard output (stdout).
266 /// This struct is used in the [`stdout`] field on [`Child`].
268 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
269 /// underlying file handle will be closed.
271 /// [`Child`]: struct.Child.html
272 /// [`stdout`]: struct.Child.html#structfield.stdout
273 /// [dropped]: ../ops/trait.Drop.html
274 #[stable(feature = "process", since = "1.0.0")]
275 pub struct ChildStdout {
279 #[stable(feature = "process", since = "1.0.0")]
280 impl Read for ChildStdout {
281 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
285 unsafe fn initializer(&self) -> Initializer {
290 impl AsInner<AnonPipe> for ChildStdout {
291 fn as_inner(&self) -> &AnonPipe { &self.inner }
294 impl IntoInner<AnonPipe> for ChildStdout {
295 fn into_inner(self) -> AnonPipe { self.inner }
298 impl FromInner<AnonPipe> for ChildStdout {
299 fn from_inner(pipe: AnonPipe) -> ChildStdout {
300 ChildStdout { inner: pipe }
304 #[stable(feature = "std_debug", since = "1.16.0")]
305 impl fmt::Debug for ChildStdout {
306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307 f.pad("ChildStdout { .. }")
311 /// A handle to a child process's stderr.
313 /// This struct is used in the [`stderr`] field on [`Child`].
315 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
316 /// underlying file handle will be closed.
318 /// [`Child`]: struct.Child.html
319 /// [`stderr`]: struct.Child.html#structfield.stderr
320 /// [dropped]: ../ops/trait.Drop.html
321 #[stable(feature = "process", since = "1.0.0")]
322 pub struct ChildStderr {
326 #[stable(feature = "process", since = "1.0.0")]
327 impl Read for ChildStderr {
328 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
332 unsafe fn initializer(&self) -> Initializer {
337 impl AsInner<AnonPipe> for ChildStderr {
338 fn as_inner(&self) -> &AnonPipe { &self.inner }
341 impl IntoInner<AnonPipe> for ChildStderr {
342 fn into_inner(self) -> AnonPipe { self.inner }
345 impl FromInner<AnonPipe> for ChildStderr {
346 fn from_inner(pipe: AnonPipe) -> ChildStderr {
347 ChildStderr { inner: pipe }
351 #[stable(feature = "std_debug", since = "1.16.0")]
352 impl fmt::Debug for ChildStderr {
353 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
354 f.pad("ChildStderr { .. }")
358 /// A process builder, providing fine-grained control
359 /// over how a new process should be spawned.
361 /// A default configuration can be
362 /// generated using `Command::new(program)`, where `program` gives a path to the
363 /// program to be executed. Additional builder methods allow the configuration
364 /// to be changed (for example, by adding arguments) prior to spawning:
367 /// use std::process::Command;
369 /// let output = if cfg!(target_os = "windows") {
370 /// Command::new("cmd")
371 /// .args(&["/C", "echo hello"])
373 /// .expect("failed to execute process")
375 /// Command::new("sh")
377 /// .arg("echo hello")
379 /// .expect("failed to execute process")
382 /// let hello = output.stdout;
384 #[stable(feature = "process", since = "1.0.0")]
390 /// Constructs a new `Command` for launching the program at
391 /// path `program`, with the following default configuration:
393 /// * No arguments to the program
394 /// * Inherit the current process's environment
395 /// * Inherit the current process's working directory
396 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
398 /// Builder methods are provided to change these defaults and
399 /// otherwise configure the process.
401 /// If `program` is not an absolute path, the `PATH` will be searched in
402 /// an OS-defined way.
404 /// The search path to be used may be controlled by setting the
405 /// `PATH` environment variable on the Command,
406 /// but this has some implementation limitations on Windows
407 /// (see <https://github.com/rust-lang/rust/issues/37519>).
414 /// use std::process::Command;
416 /// Command::new("sh")
418 /// .expect("sh command failed to start");
420 #[stable(feature = "process", since = "1.0.0")]
421 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
422 Command { inner: imp::Command::new(program.as_ref()) }
425 /// Add an argument to pass to the program.
427 /// Only one argument can be passed per use. So instead of:
430 /// # std::process::Command::new("sh")
431 /// .arg("-C /path/to/repo")
438 /// # std::process::Command::new("sh")
440 /// .arg("/path/to/repo")
444 /// To pass multiple arguments see [`args`].
446 /// [`args`]: #method.args
453 /// use std::process::Command;
455 /// Command::new("ls")
459 /// .expect("ls command failed to start");
461 #[stable(feature = "process", since = "1.0.0")]
462 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
463 self.inner.arg(arg.as_ref());
467 /// Add multiple arguments to pass to the program.
469 /// To pass a single argument see [`arg`].
471 /// [`arg`]: #method.arg
478 /// use std::process::Command;
480 /// Command::new("ls")
481 /// .args(&["-l", "-a"])
483 /// .expect("ls command failed to start");
485 #[stable(feature = "process", since = "1.0.0")]
486 pub fn args<I, S>(&mut self, args: I) -> &mut Command
487 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
490 self.arg(arg.as_ref());
495 /// Inserts or updates an environment variable mapping.
497 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
498 /// and case-sensitive on all other platforms.
505 /// use std::process::Command;
507 /// Command::new("ls")
508 /// .env("PATH", "/bin")
510 /// .expect("ls command failed to start");
512 #[stable(feature = "process", since = "1.0.0")]
513 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
514 where K: AsRef<OsStr>, V: AsRef<OsStr>
516 self.inner.env_mut().set(key.as_ref(), val.as_ref());
520 /// Add or update multiple environment variable mappings.
527 /// use std::process::{Command, Stdio};
529 /// use std::collections::HashMap;
531 /// let filtered_env : HashMap<String, String> =
532 /// env::vars().filter(|&(ref k, _)|
533 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
536 /// Command::new("printenv")
537 /// .stdin(Stdio::null())
538 /// .stdout(Stdio::inherit())
540 /// .envs(&filtered_env)
542 /// .expect("printenv failed to start");
544 #[stable(feature = "command_envs", since = "1.19.0")]
545 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
546 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
548 for (ref key, ref val) in vars {
549 self.inner.env_mut().set(key.as_ref(), val.as_ref());
554 /// Removes an environment variable mapping.
561 /// use std::process::Command;
563 /// Command::new("ls")
564 /// .env_remove("PATH")
566 /// .expect("ls command failed to start");
568 #[stable(feature = "process", since = "1.0.0")]
569 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
570 self.inner.env_mut().remove(key.as_ref());
574 /// Clears the entire environment map for the child process.
581 /// use std::process::Command;
583 /// Command::new("ls")
586 /// .expect("ls command failed to start");
588 #[stable(feature = "process", since = "1.0.0")]
589 pub fn env_clear(&mut self) -> &mut Command {
590 self.inner.env_mut().clear();
594 /// Sets the working directory for the child process.
601 /// use std::process::Command;
603 /// Command::new("ls")
604 /// .current_dir("/bin")
606 /// .expect("ls command failed to start");
608 #[stable(feature = "process", since = "1.0.0")]
609 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
610 self.inner.cwd(dir.as_ref().as_ref());
614 /// Configuration for the child process's standard input (stdin) handle.
616 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
617 /// defaults to [`piped`] when used with `output`.
619 /// [`inherit`]: struct.Stdio.html#method.inherit
620 /// [`piped`]: struct.Stdio.html#method.piped
627 /// use std::process::{Command, Stdio};
629 /// Command::new("ls")
630 /// .stdin(Stdio::null())
632 /// .expect("ls command failed to start");
634 #[stable(feature = "process", since = "1.0.0")]
635 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
636 self.inner.stdin(cfg.into().0);
640 /// Configuration for the child process's standard output (stdout) handle.
642 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
643 /// defaults to [`piped`] when used with `output`.
645 /// [`inherit`]: struct.Stdio.html#method.inherit
646 /// [`piped`]: struct.Stdio.html#method.piped
653 /// use std::process::{Command, Stdio};
655 /// Command::new("ls")
656 /// .stdout(Stdio::null())
658 /// .expect("ls command failed to start");
660 #[stable(feature = "process", since = "1.0.0")]
661 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
662 self.inner.stdout(cfg.into().0);
666 /// Configuration for the child process's standard error (stderr) handle.
668 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
669 /// defaults to [`piped`] when used with `output`.
671 /// [`inherit`]: struct.Stdio.html#method.inherit
672 /// [`piped`]: struct.Stdio.html#method.piped
679 /// use std::process::{Command, Stdio};
681 /// Command::new("ls")
682 /// .stderr(Stdio::null())
684 /// .expect("ls command failed to start");
686 #[stable(feature = "process", since = "1.0.0")]
687 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
688 self.inner.stderr(cfg.into().0);
692 /// Executes the command as a child process, returning a handle to it.
694 /// By default, stdin, stdout and stderr are inherited from the parent.
701 /// use std::process::Command;
703 /// Command::new("ls")
705 /// .expect("ls command failed to start");
707 #[stable(feature = "process", since = "1.0.0")]
708 pub fn spawn(&mut self) -> io::Result<Child> {
709 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
712 /// Executes the command as a child process, waiting for it to finish and
713 /// collecting all of its output.
715 /// By default, stdout and stderr are captured (and used to provide the
716 /// resulting output). Stdin is not inherited from the parent and any
717 /// attempt by the child process to read from the stdin stream will result
718 /// in the stream immediately closing.
723 /// use std::process::Command;
724 /// let output = Command::new("/bin/cat")
727 /// .expect("failed to execute process");
729 /// println!("status: {}", output.status);
730 /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
731 /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
733 /// assert!(output.status.success());
735 #[stable(feature = "process", since = "1.0.0")]
736 pub fn output(&mut self) -> io::Result<Output> {
737 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
738 .and_then(|p| p.wait_with_output())
741 /// Executes a command as a child process, waiting for it to finish and
742 /// collecting its exit status.
744 /// By default, stdin, stdout and stderr are inherited from the parent.
749 /// use std::process::Command;
751 /// let status = Command::new("/bin/cat")
754 /// .expect("failed to execute process");
756 /// println!("process exited with: {}", status);
758 /// assert!(status.success());
760 #[stable(feature = "process", since = "1.0.0")]
761 pub fn status(&mut self) -> io::Result<ExitStatus> {
762 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
763 .and_then(|mut p| p.wait())
767 #[stable(feature = "rust1", since = "1.0.0")]
768 impl fmt::Debug for Command {
769 /// Format the program and arguments of a Command for display. Any
770 /// non-utf8 data is lossily converted using the utf8 replacement
772 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777 impl AsInner<imp::Command> for Command {
778 fn as_inner(&self) -> &imp::Command { &self.inner }
781 impl AsInnerMut<imp::Command> for Command {
782 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
785 /// The output of a finished process.
787 /// This is returned in a Result by either the [`output`] method of a
788 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
791 /// [`Command`]: struct.Command.html
792 /// [`Child`]: struct.Child.html
793 /// [`output`]: struct.Command.html#method.output
794 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
795 #[derive(PartialEq, Eq, Clone)]
796 #[stable(feature = "process", since = "1.0.0")]
798 /// The status (exit code) of the process.
799 #[stable(feature = "process", since = "1.0.0")]
800 pub status: ExitStatus,
801 /// The data that the process wrote to stdout.
802 #[stable(feature = "process", since = "1.0.0")]
804 /// The data that the process wrote to stderr.
805 #[stable(feature = "process", since = "1.0.0")]
809 // If either stderr or stdout are valid utf8 strings it prints the valid
810 // strings, otherwise it prints the byte sequence instead
811 #[stable(feature = "process_output_debug", since = "1.7.0")]
812 impl fmt::Debug for Output {
813 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
815 let stdout_utf8 = str::from_utf8(&self.stdout);
816 let stdout_debug: &fmt::Debug = match stdout_utf8 {
818 Err(_) => &self.stdout
821 let stderr_utf8 = str::from_utf8(&self.stderr);
822 let stderr_debug: &fmt::Debug = match stderr_utf8 {
824 Err(_) => &self.stderr
827 fmt.debug_struct("Output")
828 .field("status", &self.status)
829 .field("stdout", stdout_debug)
830 .field("stderr", stderr_debug)
835 /// Describes what to do with a standard I/O stream for a child process when
836 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
838 /// [`stdin`]: struct.Command.html#method.stdin
839 /// [`stdout`]: struct.Command.html#method.stdout
840 /// [`stderr`]: struct.Command.html#method.stderr
841 /// [`Command`]: struct.Command.html
842 #[stable(feature = "process", since = "1.0.0")]
843 pub struct Stdio(imp::Stdio);
846 /// A new pipe should be arranged to connect the parent and child processes.
853 /// use std::process::{Command, Stdio};
855 /// let output = Command::new("echo")
856 /// .arg("Hello, world!")
857 /// .stdout(Stdio::piped())
859 /// .expect("Failed to execute command");
861 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
862 /// // Nothing echoed to console
868 /// use std::io::Write;
869 /// use std::process::{Command, Stdio};
871 /// let mut child = Command::new("rev")
872 /// .stdin(Stdio::piped())
873 /// .stdout(Stdio::piped())
875 /// .expect("Failed to spawn child process");
878 /// let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
879 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
882 /// let output = child.wait_with_output().expect("Failed to read stdout");
883 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
885 #[stable(feature = "process", since = "1.0.0")]
886 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
888 /// The child inherits from the corresponding parent descriptor.
895 /// use std::process::{Command, Stdio};
897 /// let output = Command::new("echo")
898 /// .arg("Hello, world!")
899 /// .stdout(Stdio::inherit())
901 /// .expect("Failed to execute command");
903 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
904 /// // "Hello, world!" echoed to console
910 /// use std::process::{Command, Stdio};
912 /// let output = Command::new("rev")
913 /// .stdin(Stdio::inherit())
914 /// .stdout(Stdio::piped())
916 /// .expect("Failed to execute command");
918 /// println!("You piped in the reverse of: {}", String::from_utf8_lossy(&output.stdout));
920 #[stable(feature = "process", since = "1.0.0")]
921 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
923 /// This stream will be ignored. This is the equivalent of attaching the
924 /// stream to `/dev/null`
931 /// use std::process::{Command, Stdio};
933 /// let output = Command::new("echo")
934 /// .arg("Hello, world!")
935 /// .stdout(Stdio::null())
937 /// .expect("Failed to execute command");
939 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
940 /// // Nothing echoed to console
946 /// use std::process::{Command, Stdio};
948 /// let output = Command::new("rev")
949 /// .stdin(Stdio::null())
950 /// .stdout(Stdio::piped())
952 /// .expect("Failed to execute command");
954 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
955 /// // Ignores any piped-in input
957 #[stable(feature = "process", since = "1.0.0")]
958 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
961 impl FromInner<imp::Stdio> for Stdio {
962 fn from_inner(inner: imp::Stdio) -> Stdio {
967 #[stable(feature = "std_debug", since = "1.16.0")]
968 impl fmt::Debug for Stdio {
969 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
970 f.pad("Stdio { .. }")
974 #[stable(feature = "stdio_from", since = "1.20.0")]
975 impl From<ChildStdin> for Stdio {
976 fn from(child: ChildStdin) -> Stdio {
977 Stdio::from_inner(child.into_inner().into())
981 #[stable(feature = "stdio_from", since = "1.20.0")]
982 impl From<ChildStdout> for Stdio {
983 fn from(child: ChildStdout) -> Stdio {
984 Stdio::from_inner(child.into_inner().into())
988 #[stable(feature = "stdio_from", since = "1.20.0")]
989 impl From<ChildStderr> for Stdio {
990 fn from(child: ChildStderr) -> Stdio {
991 Stdio::from_inner(child.into_inner().into())
995 #[stable(feature = "stdio_from", since = "1.20.0")]
996 impl From<fs::File> for Stdio {
997 fn from(file: fs::File) -> Stdio {
998 Stdio::from_inner(file.into_inner().into())
1002 /// Describes the result of a process after it has terminated.
1004 /// This `struct` is used to represent the exit status of a child process.
1005 /// Child processes are created via the [`Command`] struct and their exit
1006 /// status is exposed through the [`status`] method.
1008 /// [`Command`]: struct.Command.html
1009 /// [`status`]: struct.Command.html#method.status
1010 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1011 #[stable(feature = "process", since = "1.0.0")]
1012 pub struct ExitStatus(imp::ExitStatus);
1015 /// Was termination successful? Signal termination is not considered a
1016 /// success, and success is defined as a zero exit status.
1021 /// use std::process::Command;
1023 /// let status = Command::new("mkdir")
1024 /// .arg("projects")
1026 /// .expect("failed to execute mkdir");
1028 /// if status.success() {
1029 /// println!("'projects/' directory created");
1031 /// println!("failed to create 'projects/' directory");
1034 #[stable(feature = "process", since = "1.0.0")]
1035 pub fn success(&self) -> bool {
1039 /// Returns the exit code of the process, if any.
1041 /// On Unix, this will return `None` if the process was terminated
1042 /// by a signal; `std::os::unix` provides an extension trait for
1043 /// extracting the signal and other details from the `ExitStatus`.
1048 /// use std::process::Command;
1050 /// let status = Command::new("mkdir")
1051 /// .arg("projects")
1053 /// .expect("failed to execute mkdir");
1055 /// match status.code() {
1056 /// Some(code) => println!("Exited with status code: {}", code),
1057 /// None => println!("Process terminated by signal")
1060 #[stable(feature = "process", since = "1.0.0")]
1061 pub fn code(&self) -> Option<i32> {
1066 impl AsInner<imp::ExitStatus> for ExitStatus {
1067 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
1070 impl FromInner<imp::ExitStatus> for ExitStatus {
1071 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1076 #[stable(feature = "process", since = "1.0.0")]
1077 impl fmt::Display for ExitStatus {
1078 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1083 /// This type represents the status code a process can return to its
1084 /// parent under normal termination.
1086 /// Numeric values used in this type don't have portable meanings, and
1087 /// different platforms may mask different amounts of them.
1089 /// For the platform's canonical successful and unsuccessful codes, see
1090 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1092 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1093 /// [`FAILURE`]: #associatedconstant.FAILURE
1095 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1096 /// it was ultimately cut from that RFC, and thus this type is more subject
1097 /// to change even than the usual unstable item churn.
1099 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1100 #[derive(Clone, Copy, Debug)]
1101 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1102 pub struct ExitCode(imp::ExitCode);
1104 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1106 /// The canonical ExitCode for successful termination on this platform.
1108 /// Note that a `()`-returning `main` implicitly results in a successful
1109 /// termination, so there's no need to return this from `main` unless
1110 /// you're also returning other possible codes.
1111 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1112 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1114 /// The canonical ExitCode for unsuccessful termination on this platform.
1116 /// If you're only returning this and `SUCCESS` from `main`, consider
1117 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1118 /// return the same codes (but will also `eprintln!` the error).
1119 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1120 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1124 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1125 /// error is returned.
1127 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1128 /// especially the [`Other`] kind might change to more specific kinds in the future.
1130 /// This is equivalent to sending a SIGKILL on Unix platforms.
1137 /// use std::process::Command;
1139 /// let mut command = Command::new("yes");
1140 /// if let Ok(mut child) = command.spawn() {
1141 /// child.kill().expect("command wasn't running");
1143 /// println!("yes command didn't start");
1147 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1148 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1149 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1150 #[stable(feature = "process", since = "1.0.0")]
1151 pub fn kill(&mut self) -> io::Result<()> {
1155 /// Returns the OS-assigned process identifier associated with this child.
1162 /// use std::process::Command;
1164 /// let mut command = Command::new("ls");
1165 /// if let Ok(child) = command.spawn() {
1166 /// println!("Child's id is {}", child.id());
1168 /// println!("ls command didn't start");
1171 #[stable(feature = "process_id", since = "1.3.0")]
1172 pub fn id(&self) -> u32 {
1176 /// Waits for the child to exit completely, returning the status that it
1177 /// exited with. This function will continue to have the same return value
1178 /// after it has been called at least once.
1180 /// The stdin handle to the child process, if any, will be closed
1181 /// before waiting. This helps avoid deadlock: it ensures that the
1182 /// child does not block waiting for input from the parent, while
1183 /// the parent waits for the child to exit.
1190 /// use std::process::Command;
1192 /// let mut command = Command::new("ls");
1193 /// if let Ok(mut child) = command.spawn() {
1194 /// child.wait().expect("command wasn't running");
1195 /// println!("Child has finished its execution!");
1197 /// println!("ls command didn't start");
1200 #[stable(feature = "process", since = "1.0.0")]
1201 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1202 drop(self.stdin.take());
1203 self.handle.wait().map(ExitStatus)
1206 /// Attempts to collect the exit status of the child if it has already
1209 /// This function will not block the calling thread and will only advisorily
1210 /// check to see if the child process has exited or not. If the child has
1211 /// exited then on Unix the process id is reaped. This function is
1212 /// guaranteed to repeatedly return a successful exit status so long as the
1213 /// child has already exited.
1215 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1216 /// exit status is not available at this time then `Ok(None)` is returned.
1217 /// If an error occurs, then that error is returned.
1219 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1226 /// use std::process::Command;
1228 /// let mut child = Command::new("ls").spawn().unwrap();
1230 /// match child.try_wait() {
1231 /// Ok(Some(status)) => println!("exited with: {}", status),
1233 /// println!("status not ready yet, let's really wait");
1234 /// let res = child.wait();
1235 /// println!("result: {:?}", res);
1237 /// Err(e) => println!("error attempting to wait: {}", e),
1240 #[stable(feature = "process_try_wait", since = "1.18.0")]
1241 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1242 Ok(self.handle.try_wait()?.map(ExitStatus))
1245 /// Simultaneously waits for the child to exit and collect all remaining
1246 /// output on the stdout/stderr handles, returning an `Output`
1249 /// The stdin handle to the child process, if any, will be closed
1250 /// before waiting. This helps avoid deadlock: it ensures that the
1251 /// child does not block waiting for input from the parent, while
1252 /// the parent waits for the child to exit.
1254 /// By default, stdin, stdout and stderr are inherited from the parent.
1255 /// In order to capture the output into this `Result<Output>` it is
1256 /// necessary to create new pipes between parent and child. Use
1257 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1262 /// use std::process::{Command, Stdio};
1264 /// let child = Command::new("/bin/cat")
1265 /// .arg("file.txt")
1266 /// .stdout(Stdio::piped())
1268 /// .expect("failed to execute child");
1270 /// let output = child
1271 /// .wait_with_output()
1272 /// .expect("failed to wait on child");
1274 /// assert!(output.status.success());
1277 #[stable(feature = "process", since = "1.0.0")]
1278 pub fn wait_with_output(mut self) -> io::Result<Output> {
1279 drop(self.stdin.take());
1281 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1282 match (self.stdout.take(), self.stderr.take()) {
1284 (Some(mut out), None) => {
1285 let res = out.read_to_end(&mut stdout);
1288 (None, Some(mut err)) => {
1289 let res = err.read_to_end(&mut stderr);
1292 (Some(out), Some(err)) => {
1293 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1298 let status = self.wait()?;
1307 /// Terminates the current process with the specified exit code.
1309 /// This function will never return and will immediately terminate the current
1310 /// process. The exit code is passed through to the underlying OS and will be
1311 /// available for consumption by another process.
1313 /// Note that because this function never returns, and that it terminates the
1314 /// process, no destructors on the current stack or any other thread's stack
1315 /// will be run. If a clean shutdown is needed it is recommended to only call
1316 /// this function at a known point where there are no more destructors left
1319 /// ## Platform-specific behavior
1321 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1322 /// will be visible to a parent process inspecting the exit code. On most
1323 /// Unix-like platforms, only the eight least-significant bits are considered.
1327 /// Due to this function’s behavior regarding destructors, a conventional way
1328 /// to use the function is to extract the actual computation to another
1329 /// function and compute the exit code from its return value:
1332 /// fn run_app() -> Result<(), ()> {
1333 /// // Application logic here
1338 /// ::std::process::exit(match run_app() {
1341 /// eprintln!("error: {:?}", err);
1348 /// Due to [platform-specific behavior], the exit code for this example will be
1349 /// `0` on Linux, but `256` on Windows:
1352 /// use std::process;
1354 /// process::exit(0x0100);
1357 /// [platform-specific behavior]: #platform-specific-behavior
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn exit(code: i32) -> ! {
1360 ::sys_common::cleanup();
1361 ::sys::os::exit(code)
1364 /// Terminates the process in an abnormal fashion.
1366 /// The function will never return and will immediately terminate the current
1367 /// process in a platform specific "abnormal" manner.
1369 /// Note that because this function never returns, and that it terminates the
1370 /// process, no destructors on the current stack or any other thread's stack
1373 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1374 /// the current thread's stack and calls all destructors.
1375 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1376 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1377 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1379 /// If a clean shutdown is needed it is recommended to only call
1380 /// this function at a known point where there are no more destructors left
1386 /// use std::process;
1389 /// println!("aborting");
1391 /// process::abort();
1393 /// // execution never gets here
1397 /// The `abort` function terminates the process, so the destructor will not
1398 /// get run on the example below:
1401 /// use std::process;
1405 /// impl Drop for HasDrop {
1406 /// fn drop(&mut self) {
1407 /// println!("This will never be printed!");
1412 /// let _x = HasDrop;
1413 /// process::abort();
1414 /// // the destructor implemented for HasDrop will never get run
1418 /// [`panic!`]: ../../std/macro.panic.html
1419 /// [panic hook]: ../../std/panic/fn.set_hook.html
1420 #[stable(feature = "process_abort", since = "1.17.0")]
1421 pub fn abort() -> ! {
1422 unsafe { ::sys::abort_internal() };
1425 /// Returns the OS-assigned process identifier associated with this process.
1432 /// use std::process;
1434 /// println!("My pid is {}", process::id());
1438 #[stable(feature = "getpid", since = "1.26.0")]
1439 pub fn id() -> u32 {
1443 /// A trait for implementing arbitrary return types in the `main` function.
1445 /// The c-main function only supports to return integers as return type.
1446 /// So, every type implementing the `Termination` trait has to be converted
1449 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1450 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1451 #[cfg_attr(not(test), lang = "termination")]
1452 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1453 #[rustc_on_unimplemented(
1454 message="`main` has invalid return type `{Self}`",
1455 label="`main` can only return types that implement `{Termination}`")]
1456 pub trait Termination {
1457 /// Is called to get the representation of the value as status code.
1458 /// This status code is returned to the operating system.
1459 fn report(self) -> i32;
1462 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1463 impl Termination for () {
1465 fn report(self) -> i32 { ExitCode::SUCCESS.report() }
1468 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1469 impl<E: fmt::Debug> Termination for Result<(), E> {
1470 fn report(self) -> i32 {
1472 Ok(()) => ().report(),
1473 Err(err) => Err::<!, _>(err).report(),
1478 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1479 impl Termination for ! {
1480 fn report(self) -> i32 { self }
1483 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1484 impl<E: fmt::Debug> Termination for Result<!, E> {
1485 fn report(self) -> i32 {
1486 let Err(err) = self;
1487 eprintln!("Error: {:?}", err);
1488 ExitCode::FAILURE.report()
1492 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1493 impl Termination for ExitCode {
1495 fn report(self) -> i32 {
1500 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
1506 use super::{Command, Output, Stdio};
1508 // FIXME(#10380) these tests should not all be ignored on android.
1511 #[cfg_attr(target_os = "android", ignore)]
1513 let p = if cfg!(target_os = "windows") {
1514 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1516 Command::new("true").spawn()
1519 let mut p = p.unwrap();
1520 assert!(p.wait().unwrap().success());
1524 #[cfg_attr(target_os = "android", ignore)]
1525 fn smoke_failure() {
1526 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1533 #[cfg_attr(target_os = "android", ignore)]
1534 fn exit_reported_right() {
1535 let p = if cfg!(target_os = "windows") {
1536 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1538 Command::new("false").spawn()
1541 let mut p = p.unwrap();
1542 assert!(p.wait().unwrap().code() == Some(1));
1548 #[cfg_attr(target_os = "android", ignore)]
1549 fn signal_reported_right() {
1550 use os::unix::process::ExitStatusExt;
1552 let mut p = Command::new("/bin/sh")
1553 .arg("-c").arg("read a")
1554 .stdin(Stdio::piped())
1557 match p.wait().unwrap().signal() {
1559 result => panic!("not terminated by signal 9 (instead, {:?})",
1564 pub fn run_output(mut cmd: Command) -> String {
1565 let p = cmd.spawn();
1567 let mut p = p.unwrap();
1568 assert!(p.stdout.is_some());
1569 let mut ret = String::new();
1570 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1571 assert!(p.wait().unwrap().success());
1576 #[cfg_attr(target_os = "android", ignore)]
1578 if cfg!(target_os = "windows") {
1579 let mut cmd = Command::new("cmd");
1580 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1581 assert_eq!(run_output(cmd), "foobar\r\n");
1583 let mut cmd = Command::new("echo");
1584 cmd.arg("foobar").stdout(Stdio::piped());
1585 assert_eq!(run_output(cmd), "foobar\n");
1590 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1591 fn set_current_dir_works() {
1592 let mut cmd = Command::new("/bin/sh");
1593 cmd.arg("-c").arg("pwd")
1595 .stdout(Stdio::piped());
1596 assert_eq!(run_output(cmd), "/\n");
1600 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1602 let mut p = Command::new("/bin/sh")
1603 .arg("-c").arg("read line; echo $line")
1604 .stdin(Stdio::piped())
1605 .stdout(Stdio::piped())
1607 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1608 drop(p.stdin.take());
1609 let mut out = String::new();
1610 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1611 assert!(p.wait().unwrap().success());
1612 assert_eq!(out, "foobar\n");
1617 #[cfg_attr(target_os = "android", ignore)]
1620 use os::unix::prelude::*;
1622 let mut p = Command::new("/bin/sh")
1623 .arg("-c").arg("true")
1624 .uid(unsafe { libc::getuid() })
1625 .gid(unsafe { libc::getgid() })
1627 assert!(p.wait().unwrap().success());
1631 #[cfg_attr(target_os = "android", ignore)]
1633 fn uid_to_root_fails() {
1634 use os::unix::prelude::*;
1637 // if we're already root, this isn't a valid test. Most of the bots run
1638 // as non-root though (android is an exception).
1639 if unsafe { libc::getuid() == 0 } { return }
1640 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1644 #[cfg_attr(target_os = "android", ignore)]
1645 fn test_process_status() {
1646 let mut status = if cfg!(target_os = "windows") {
1647 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1649 Command::new("false").status().unwrap()
1651 assert!(status.code() == Some(1));
1653 status = if cfg!(target_os = "windows") {
1654 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1656 Command::new("true").status().unwrap()
1658 assert!(status.success());
1662 fn test_process_output_fail_to_start() {
1663 match Command::new("/no-binary-by-this-name-should-exist").output() {
1664 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1670 #[cfg_attr(target_os = "android", ignore)]
1671 fn test_process_output_output() {
1672 let Output {status, stdout, stderr}
1673 = if cfg!(target_os = "windows") {
1674 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1676 Command::new("echo").arg("hello").output().unwrap()
1678 let output_str = str::from_utf8(&stdout).unwrap();
1680 assert!(status.success());
1681 assert_eq!(output_str.trim().to_string(), "hello");
1682 assert_eq!(stderr, Vec::new());
1686 #[cfg_attr(target_os = "android", ignore)]
1687 fn test_process_output_error() {
1688 let Output {status, stdout, stderr}
1689 = if cfg!(target_os = "windows") {
1690 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1692 Command::new("mkdir").arg("./").output().unwrap()
1695 assert!(status.code() == Some(1));
1696 assert_eq!(stdout, Vec::new());
1697 assert!(!stderr.is_empty());
1701 #[cfg_attr(target_os = "android", ignore)]
1702 fn test_finish_once() {
1703 let mut prog = if cfg!(target_os = "windows") {
1704 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1706 Command::new("false").spawn().unwrap()
1708 assert!(prog.wait().unwrap().code() == Some(1));
1712 #[cfg_attr(target_os = "android", ignore)]
1713 fn test_finish_twice() {
1714 let mut prog = if cfg!(target_os = "windows") {
1715 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1717 Command::new("false").spawn().unwrap()
1719 assert!(prog.wait().unwrap().code() == Some(1));
1720 assert!(prog.wait().unwrap().code() == Some(1));
1724 #[cfg_attr(target_os = "android", ignore)]
1725 fn test_wait_with_output_once() {
1726 let prog = if cfg!(target_os = "windows") {
1727 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1729 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1732 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1733 let output_str = str::from_utf8(&stdout).unwrap();
1735 assert!(status.success());
1736 assert_eq!(output_str.trim().to_string(), "hello");
1737 assert_eq!(stderr, Vec::new());
1740 #[cfg(all(unix, not(target_os="android")))]
1741 pub fn env_cmd() -> Command {
1744 #[cfg(target_os="android")]
1745 pub fn env_cmd() -> Command {
1746 let mut cmd = Command::new("/system/bin/sh");
1747 cmd.arg("-c").arg("set");
1752 pub fn env_cmd() -> Command {
1753 let mut cmd = Command::new("cmd");
1754 cmd.arg("/c").arg("set");
1759 fn test_inherit_env() {
1762 let result = env_cmd().output().unwrap();
1763 let output = String::from_utf8(result.stdout).unwrap();
1765 for (ref k, ref v) in env::vars() {
1766 // Don't check android RANDOM variable which seems to change
1767 // whenever the shell runs, and our `env_cmd` is indeed running a
1768 // shell which means it'll get a different RANDOM than we probably
1771 // Also skip env vars with `-` in the name on android because, well,
1772 // I'm not sure. It appears though that the `set` command above does
1773 // not print env vars with `-` in the name, so we just skip them
1774 // here as we won't find them in the output. Note that most env vars
1775 // use `_` instead of `-`, but our build system sets a few env vars
1776 // with `-` in the name.
1777 if cfg!(target_os = "android") &&
1778 (*k == "RANDOM" || k.contains("-")) {
1782 // Windows has hidden environment variables whose names start with
1783 // equals signs (`=`). Those do not show up in the output of the
1785 assert!((cfg!(windows) && k.starts_with("=")) ||
1786 k.starts_with("DYLD") ||
1787 output.contains(&format!("{}={}", *k, *v)) ||
1788 output.contains(&format!("{}='{}'", *k, *v)),
1789 "output doesn't contain `{}={}`\n{}",
1795 fn test_override_env() {
1798 // In some build environments (such as chrooted Nix builds), `env` can
1799 // only be found in the explicitly-provided PATH env variable, not in
1800 // default places such as /bin or /usr/bin. So we need to pass through
1801 // PATH to our sub-process.
1802 let mut cmd = env_cmd();
1803 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1804 if let Some(p) = env::var_os("PATH") {
1805 cmd.env("PATH", &p);
1807 let result = cmd.output().unwrap();
1808 let output = String::from_utf8_lossy(&result.stdout).to_string();
1810 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1811 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1815 fn test_add_to_env() {
1816 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1817 let output = String::from_utf8_lossy(&result.stdout).to_string();
1819 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1820 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1824 fn test_capture_env_at_spawn() {
1827 let mut cmd = env_cmd();
1828 cmd.env("RUN_TEST_NEW_ENV1", "123");
1830 // This variable will not be present if the environment has already
1831 // been captured above.
1832 env::set_var("RUN_TEST_NEW_ENV2", "456");
1833 let result = cmd.output().unwrap();
1834 env::remove_var("RUN_TEST_NEW_ENV2");
1836 let output = String::from_utf8_lossy(&result.stdout).to_string();
1838 assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1839 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1840 assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1841 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1844 // Regression tests for #30858.
1846 fn test_interior_nul_in_progname_is_error() {
1847 match Command::new("has-some-\0\0s-inside").spawn() {
1848 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1854 fn test_interior_nul_in_arg_is_error() {
1855 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1856 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1862 fn test_interior_nul_in_args_is_error() {
1863 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1864 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1870 fn test_interior_nul_in_current_dir_is_error() {
1871 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1872 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1877 // Regression tests for #30862.
1879 fn test_interior_nul_in_env_key_is_error() {
1880 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1881 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1887 fn test_interior_nul_in_env_value_is_error() {
1888 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1889 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1894 /// Test that process creation flags work by debugging a process.
1895 /// Other creation flags make it hard or impossible to detect
1896 /// behavioral changes in the process.
1899 fn test_creation_flags() {
1900 use os::windows::process::CommandExt;
1901 use sys::c::{BOOL, DWORD, INFINITE};
1903 struct DEBUG_EVENT {
1904 pub event_code: DWORD,
1905 pub process_id: DWORD,
1906 pub thread_id: DWORD,
1907 // This is a union in the real struct, but we don't
1908 // need this data for the purposes of this test.
1909 pub _junk: [u8; 164],
1913 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1914 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1915 dwContinueStatus: DWORD) -> BOOL;
1918 const DEBUG_PROCESS: DWORD = 1;
1919 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1920 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1922 let mut child = Command::new("cmd")
1923 .creation_flags(DEBUG_PROCESS)
1924 .stdin(Stdio::piped()).spawn().unwrap();
1925 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1927 let mut event = DEBUG_EVENT {
1934 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1935 panic!("WaitForDebugEvent failed!");
1939 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1943 if unsafe { ContinueDebugEvent(event.process_id,
1945 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1946 panic!("ContinueDebugEvent failed!");
1949 assert!(events > 0);
1953 fn test_command_implements_send() {
1954 fn take_send_type<T: Send>(_: T) {}
1955 take_send_type(Command::new(""))