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;
385 /// `Command` can be reused to spawn multiple processes. The builder methods
386 /// change the command without needing to immediately spawn the process.
389 /// use std::process::Command;
391 /// let mut echo_hello = Command::new("sh");
392 /// echo_hello.arg("-c")
393 /// .arg("echo hello");
394 /// let hello_1 = echo_hello.output().expect("failed to execute process");
395 /// let hello_2 = echo_hello.output().expect("failed to execute process");
398 /// Similarly, you can call builder methods after spawning a process and then
399 /// spawn a new process with the modified settings.
402 /// use std::process::Command;
404 /// let mut list_dir = Command::new("ls");
406 /// // Execute `ls` in the current directory of the program.
407 /// list_dir.status().expect("process failed to execute");
411 /// // Change `ls` to execute in the root directory.
412 /// list_dir.current_dir("/");
414 /// // And then execute `ls` again but in the root directory.
415 /// list_dir.status().expect("process failed to execute");
417 #[stable(feature = "process", since = "1.0.0")]
423 /// Constructs a new `Command` for launching the program at
424 /// path `program`, with the following default configuration:
426 /// * No arguments to the program
427 /// * Inherit the current process's environment
428 /// * Inherit the current process's working directory
429 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
431 /// Builder methods are provided to change these defaults and
432 /// otherwise configure the process.
434 /// If `program` is not an absolute path, the `PATH` will be searched in
435 /// an OS-defined way.
437 /// The search path to be used may be controlled by setting the
438 /// `PATH` environment variable on the Command,
439 /// but this has some implementation limitations on Windows
440 /// (see <https://github.com/rust-lang/rust/issues/37519>).
447 /// use std::process::Command;
449 /// Command::new("sh")
451 /// .expect("sh command failed to start");
453 #[stable(feature = "process", since = "1.0.0")]
454 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
455 Command { inner: imp::Command::new(program.as_ref()) }
458 /// Add an argument to pass to the program.
460 /// Only one argument can be passed per use. So instead of:
463 /// # std::process::Command::new("sh")
464 /// .arg("-C /path/to/repo")
471 /// # std::process::Command::new("sh")
473 /// .arg("/path/to/repo")
477 /// To pass multiple arguments see [`args`].
479 /// [`args`]: #method.args
486 /// use std::process::Command;
488 /// Command::new("ls")
492 /// .expect("ls command failed to start");
494 #[stable(feature = "process", since = "1.0.0")]
495 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
496 self.inner.arg(arg.as_ref());
500 /// Add multiple arguments to pass to the program.
502 /// To pass a single argument see [`arg`].
504 /// [`arg`]: #method.arg
511 /// use std::process::Command;
513 /// Command::new("ls")
514 /// .args(&["-l", "-a"])
516 /// .expect("ls command failed to start");
518 #[stable(feature = "process", since = "1.0.0")]
519 pub fn args<I, S>(&mut self, args: I) -> &mut Command
520 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
523 self.arg(arg.as_ref());
528 /// Inserts or updates an environment variable mapping.
530 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
531 /// and case-sensitive on all other platforms.
538 /// use std::process::Command;
540 /// Command::new("ls")
541 /// .env("PATH", "/bin")
543 /// .expect("ls command failed to start");
545 #[stable(feature = "process", since = "1.0.0")]
546 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
547 where K: AsRef<OsStr>, V: AsRef<OsStr>
549 self.inner.env_mut().set(key.as_ref(), val.as_ref());
553 /// Add or update multiple environment variable mappings.
560 /// use std::process::{Command, Stdio};
562 /// use std::collections::HashMap;
564 /// let filtered_env : HashMap<String, String> =
565 /// env::vars().filter(|&(ref k, _)|
566 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
569 /// Command::new("printenv")
570 /// .stdin(Stdio::null())
571 /// .stdout(Stdio::inherit())
573 /// .envs(&filtered_env)
575 /// .expect("printenv failed to start");
577 #[stable(feature = "command_envs", since = "1.19.0")]
578 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
579 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
581 for (ref key, ref val) in vars {
582 self.inner.env_mut().set(key.as_ref(), val.as_ref());
587 /// Removes an environment variable mapping.
594 /// use std::process::Command;
596 /// Command::new("ls")
597 /// .env_remove("PATH")
599 /// .expect("ls command failed to start");
601 #[stable(feature = "process", since = "1.0.0")]
602 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
603 self.inner.env_mut().remove(key.as_ref());
607 /// Clears the entire environment map for the child process.
614 /// use std::process::Command;
616 /// Command::new("ls")
619 /// .expect("ls command failed to start");
621 #[stable(feature = "process", since = "1.0.0")]
622 pub fn env_clear(&mut self) -> &mut Command {
623 self.inner.env_mut().clear();
627 /// Sets the working directory for the child process.
629 /// # Platform-specific behavior
631 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
632 /// whether it should be interpreted relative to the parent's working
633 /// directory or relative to `current_dir`. The behavior in this case is
634 /// platform specific and unstable, and it's recommended to use
635 /// [`canonicalize`] to get an absolute program path instead.
642 /// use std::process::Command;
644 /// Command::new("ls")
645 /// .current_dir("/bin")
647 /// .expect("ls command failed to start");
650 /// [`canonicalize`]: ../fs/fn.canonicalize.html
651 #[stable(feature = "process", since = "1.0.0")]
652 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
653 self.inner.cwd(dir.as_ref().as_ref());
657 /// Configuration for the child process's standard input (stdin) handle.
659 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
660 /// defaults to [`piped`] when used with `output`.
662 /// [`inherit`]: struct.Stdio.html#method.inherit
663 /// [`piped`]: struct.Stdio.html#method.piped
670 /// use std::process::{Command, Stdio};
672 /// Command::new("ls")
673 /// .stdin(Stdio::null())
675 /// .expect("ls command failed to start");
677 #[stable(feature = "process", since = "1.0.0")]
678 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
679 self.inner.stdin(cfg.into().0);
683 /// Configuration for the child process's standard output (stdout) handle.
685 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
686 /// defaults to [`piped`] when used with `output`.
688 /// [`inherit`]: struct.Stdio.html#method.inherit
689 /// [`piped`]: struct.Stdio.html#method.piped
696 /// use std::process::{Command, Stdio};
698 /// Command::new("ls")
699 /// .stdout(Stdio::null())
701 /// .expect("ls command failed to start");
703 #[stable(feature = "process", since = "1.0.0")]
704 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
705 self.inner.stdout(cfg.into().0);
709 /// Configuration for the child process's standard error (stderr) handle.
711 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
712 /// defaults to [`piped`] when used with `output`.
714 /// [`inherit`]: struct.Stdio.html#method.inherit
715 /// [`piped`]: struct.Stdio.html#method.piped
722 /// use std::process::{Command, Stdio};
724 /// Command::new("ls")
725 /// .stderr(Stdio::null())
727 /// .expect("ls command failed to start");
729 #[stable(feature = "process", since = "1.0.0")]
730 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
731 self.inner.stderr(cfg.into().0);
735 /// Executes the command as a child process, returning a handle to it.
737 /// By default, stdin, stdout and stderr are inherited from the parent.
744 /// use std::process::Command;
746 /// Command::new("ls")
748 /// .expect("ls command failed to start");
750 #[stable(feature = "process", since = "1.0.0")]
751 pub fn spawn(&mut self) -> io::Result<Child> {
752 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
755 /// Executes the command as a child process, waiting for it to finish and
756 /// collecting all of its output.
758 /// By default, stdout and stderr are captured (and used to provide the
759 /// resulting output). Stdin is not inherited from the parent and any
760 /// attempt by the child process to read from the stdin stream will result
761 /// in the stream immediately closing.
766 /// use std::process::Command;
767 /// use std::io::{self, Write};
768 /// let output = Command::new("/bin/cat")
771 /// .expect("failed to execute process");
773 /// println!("status: {}", output.status);
774 /// io::stdout().write_all(&output.stdout).unwrap();
775 /// io::stderr().write_all(&output.stderr).unwrap();
777 /// assert!(output.status.success());
779 #[stable(feature = "process", since = "1.0.0")]
780 pub fn output(&mut self) -> io::Result<Output> {
781 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
782 .and_then(|p| p.wait_with_output())
785 /// Executes a command as a child process, waiting for it to finish and
786 /// collecting its exit status.
788 /// By default, stdin, stdout and stderr are inherited from the parent.
793 /// use std::process::Command;
795 /// let status = Command::new("/bin/cat")
798 /// .expect("failed to execute process");
800 /// println!("process exited with: {}", status);
802 /// assert!(status.success());
804 #[stable(feature = "process", since = "1.0.0")]
805 pub fn status(&mut self) -> io::Result<ExitStatus> {
806 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
807 .and_then(|mut p| p.wait())
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl fmt::Debug for Command {
813 /// Format the program and arguments of a Command for display. Any
814 /// non-utf8 data is lossily converted using the utf8 replacement
816 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
821 impl AsInner<imp::Command> for Command {
822 fn as_inner(&self) -> &imp::Command { &self.inner }
825 impl AsInnerMut<imp::Command> for Command {
826 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
829 /// The output of a finished process.
831 /// This is returned in a Result by either the [`output`] method of a
832 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
835 /// [`Command`]: struct.Command.html
836 /// [`Child`]: struct.Child.html
837 /// [`output`]: struct.Command.html#method.output
838 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
839 #[derive(PartialEq, Eq, Clone)]
840 #[stable(feature = "process", since = "1.0.0")]
842 /// The status (exit code) of the process.
843 #[stable(feature = "process", since = "1.0.0")]
844 pub status: ExitStatus,
845 /// The data that the process wrote to stdout.
846 #[stable(feature = "process", since = "1.0.0")]
848 /// The data that the process wrote to stderr.
849 #[stable(feature = "process", since = "1.0.0")]
853 // If either stderr or stdout are valid utf8 strings it prints the valid
854 // strings, otherwise it prints the byte sequence instead
855 #[stable(feature = "process_output_debug", since = "1.7.0")]
856 impl fmt::Debug for Output {
857 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
859 let stdout_utf8 = str::from_utf8(&self.stdout);
860 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
862 Err(_) => &self.stdout
865 let stderr_utf8 = str::from_utf8(&self.stderr);
866 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
868 Err(_) => &self.stderr
871 fmt.debug_struct("Output")
872 .field("status", &self.status)
873 .field("stdout", stdout_debug)
874 .field("stderr", stderr_debug)
879 /// Describes what to do with a standard I/O stream for a child process when
880 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
882 /// [`stdin`]: struct.Command.html#method.stdin
883 /// [`stdout`]: struct.Command.html#method.stdout
884 /// [`stderr`]: struct.Command.html#method.stderr
885 /// [`Command`]: struct.Command.html
886 #[stable(feature = "process", since = "1.0.0")]
887 pub struct Stdio(imp::Stdio);
890 /// A new pipe should be arranged to connect the parent and child processes.
897 /// use std::process::{Command, Stdio};
899 /// let output = Command::new("echo")
900 /// .arg("Hello, world!")
901 /// .stdout(Stdio::piped())
903 /// .expect("Failed to execute command");
905 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
906 /// // Nothing echoed to console
912 /// use std::io::Write;
913 /// use std::process::{Command, Stdio};
915 /// let mut child = Command::new("rev")
916 /// .stdin(Stdio::piped())
917 /// .stdout(Stdio::piped())
919 /// .expect("Failed to spawn child process");
922 /// let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
923 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
926 /// let output = child.wait_with_output().expect("Failed to read stdout");
927 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
929 #[stable(feature = "process", since = "1.0.0")]
930 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
932 /// The child inherits from the corresponding parent descriptor.
939 /// use std::process::{Command, Stdio};
941 /// let output = Command::new("echo")
942 /// .arg("Hello, world!")
943 /// .stdout(Stdio::inherit())
945 /// .expect("Failed to execute command");
947 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
948 /// // "Hello, world!" echoed to console
954 /// use std::process::{Command, Stdio};
955 /// use std::io::{self, Write};
957 /// let output = Command::new("rev")
958 /// .stdin(Stdio::inherit())
959 /// .stdout(Stdio::piped())
961 /// .expect("Failed to execute command");
963 /// print!("You piped in the reverse of: ");
964 /// io::stdout().write_all(&output.stdout).unwrap();
966 #[stable(feature = "process", since = "1.0.0")]
967 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
969 /// This stream will be ignored. This is the equivalent of attaching the
970 /// stream to `/dev/null`
977 /// use std::process::{Command, Stdio};
979 /// let output = Command::new("echo")
980 /// .arg("Hello, world!")
981 /// .stdout(Stdio::null())
983 /// .expect("Failed to execute command");
985 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
986 /// // Nothing echoed to console
992 /// use std::process::{Command, Stdio};
994 /// let output = Command::new("rev")
995 /// .stdin(Stdio::null())
996 /// .stdout(Stdio::piped())
998 /// .expect("Failed to execute command");
1000 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1001 /// // Ignores any piped-in input
1003 #[stable(feature = "process", since = "1.0.0")]
1004 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
1007 impl FromInner<imp::Stdio> for Stdio {
1008 fn from_inner(inner: imp::Stdio) -> Stdio {
1013 #[stable(feature = "std_debug", since = "1.16.0")]
1014 impl fmt::Debug for Stdio {
1015 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1016 f.pad("Stdio { .. }")
1020 #[stable(feature = "stdio_from", since = "1.20.0")]
1021 impl From<ChildStdin> for Stdio {
1022 /// Converts a `ChildStdin` into a `Stdio`
1026 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1029 /// use std::process::{Command, Stdio};
1031 /// let reverse = Command::new("rev")
1032 /// .stdin(Stdio::piped())
1034 /// .expect("failed reverse command");
1036 /// let _echo = Command::new("echo")
1037 /// .arg("Hello, world!")
1038 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1040 /// .expect("failed echo command");
1042 /// // "!dlrow ,olleH" echoed to console
1044 fn from(child: ChildStdin) -> Stdio {
1045 Stdio::from_inner(child.into_inner().into())
1049 #[stable(feature = "stdio_from", since = "1.20.0")]
1050 impl From<ChildStdout> for Stdio {
1051 /// Converts a `ChildStdout` into a `Stdio`
1055 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1058 /// use std::process::{Command, Stdio};
1060 /// let hello = Command::new("echo")
1061 /// .arg("Hello, world!")
1062 /// .stdout(Stdio::piped())
1064 /// .expect("failed echo command");
1066 /// let reverse = Command::new("rev")
1067 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1069 /// .expect("failed reverse command");
1071 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1073 fn from(child: ChildStdout) -> Stdio {
1074 Stdio::from_inner(child.into_inner().into())
1078 #[stable(feature = "stdio_from", since = "1.20.0")]
1079 impl From<ChildStderr> for Stdio {
1080 /// Converts a `ChildStderr` into a `Stdio`
1085 /// use std::process::{Command, Stdio};
1087 /// let reverse = Command::new("rev")
1088 /// .arg("non_existing_file.txt")
1089 /// .stderr(Stdio::piped())
1091 /// .expect("failed reverse command");
1093 /// let cat = Command::new("cat")
1095 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1097 /// .expect("failed echo command");
1100 /// String::from_utf8_lossy(&cat.stdout),
1101 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1104 fn from(child: ChildStderr) -> Stdio {
1105 Stdio::from_inner(child.into_inner().into())
1109 #[stable(feature = "stdio_from", since = "1.20.0")]
1110 impl From<fs::File> for Stdio {
1111 /// Converts a `File` into a `Stdio`
1115 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1118 /// use std::fs::File;
1119 /// use std::process::Command;
1121 /// // With the `foo.txt` file containing `Hello, world!"
1122 /// let file = File::open("foo.txt").unwrap();
1124 /// let reverse = Command::new("rev")
1125 /// .stdin(file) // Implicit File conversion into a Stdio
1127 /// .expect("failed reverse command");
1129 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1131 fn from(file: fs::File) -> Stdio {
1132 Stdio::from_inner(file.into_inner().into())
1136 /// Describes the result of a process after it has terminated.
1138 /// This `struct` is used to represent the exit status of a child process.
1139 /// Child processes are created via the [`Command`] struct and their exit
1140 /// status is exposed through the [`status`] method.
1142 /// [`Command`]: struct.Command.html
1143 /// [`status`]: struct.Command.html#method.status
1144 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1145 #[stable(feature = "process", since = "1.0.0")]
1146 pub struct ExitStatus(imp::ExitStatus);
1149 /// Was termination successful? Signal termination is not considered a
1150 /// success, and success is defined as a zero exit status.
1155 /// use std::process::Command;
1157 /// let status = Command::new("mkdir")
1158 /// .arg("projects")
1160 /// .expect("failed to execute mkdir");
1162 /// if status.success() {
1163 /// println!("'projects/' directory created");
1165 /// println!("failed to create 'projects/' directory");
1168 #[stable(feature = "process", since = "1.0.0")]
1169 pub fn success(&self) -> bool {
1173 /// Returns the exit code of the process, if any.
1175 /// On Unix, this will return `None` if the process was terminated
1176 /// by a signal; `std::os::unix` provides an extension trait for
1177 /// extracting the signal and other details from the `ExitStatus`.
1182 /// use std::process::Command;
1184 /// let status = Command::new("mkdir")
1185 /// .arg("projects")
1187 /// .expect("failed to execute mkdir");
1189 /// match status.code() {
1190 /// Some(code) => println!("Exited with status code: {}", code),
1191 /// None => println!("Process terminated by signal")
1194 #[stable(feature = "process", since = "1.0.0")]
1195 pub fn code(&self) -> Option<i32> {
1200 impl AsInner<imp::ExitStatus> for ExitStatus {
1201 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
1204 impl FromInner<imp::ExitStatus> for ExitStatus {
1205 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1210 #[stable(feature = "process", since = "1.0.0")]
1211 impl fmt::Display for ExitStatus {
1212 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1217 /// This type represents the status code a process can return to its
1218 /// parent under normal termination.
1220 /// Numeric values used in this type don't have portable meanings, and
1221 /// different platforms may mask different amounts of them.
1223 /// For the platform's canonical successful and unsuccessful codes, see
1224 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1226 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1227 /// [`FAILURE`]: #associatedconstant.FAILURE
1229 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1230 /// it was ultimately cut from that RFC, and thus this type is more subject
1231 /// to change even than the usual unstable item churn.
1233 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1234 #[derive(Clone, Copy, Debug)]
1235 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1236 pub struct ExitCode(imp::ExitCode);
1238 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1240 /// The canonical ExitCode for successful termination on this platform.
1242 /// Note that a `()`-returning `main` implicitly results in a successful
1243 /// termination, so there's no need to return this from `main` unless
1244 /// you're also returning other possible codes.
1245 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1246 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1248 /// The canonical ExitCode for unsuccessful termination on this platform.
1250 /// If you're only returning this and `SUCCESS` from `main`, consider
1251 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1252 /// return the same codes (but will also `eprintln!` the error).
1253 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1254 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1258 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1259 /// error is returned.
1261 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1262 /// especially the [`Other`] kind might change to more specific kinds in the future.
1264 /// This is equivalent to sending a SIGKILL on Unix platforms.
1271 /// use std::process::Command;
1273 /// let mut command = Command::new("yes");
1274 /// if let Ok(mut child) = command.spawn() {
1275 /// child.kill().expect("command wasn't running");
1277 /// println!("yes command didn't start");
1281 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1282 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1283 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1284 #[stable(feature = "process", since = "1.0.0")]
1285 pub fn kill(&mut self) -> io::Result<()> {
1289 /// Returns the OS-assigned process identifier associated with this child.
1296 /// use std::process::Command;
1298 /// let mut command = Command::new("ls");
1299 /// if let Ok(child) = command.spawn() {
1300 /// println!("Child's id is {}", child.id());
1302 /// println!("ls command didn't start");
1305 #[stable(feature = "process_id", since = "1.3.0")]
1306 pub fn id(&self) -> u32 {
1310 /// Waits for the child to exit completely, returning the status that it
1311 /// exited with. This function will continue to have the same return value
1312 /// after it has been called at least once.
1314 /// The stdin handle to the child process, if any, will be closed
1315 /// before waiting. This helps avoid deadlock: it ensures that the
1316 /// child does not block waiting for input from the parent, while
1317 /// the parent waits for the child to exit.
1324 /// use std::process::Command;
1326 /// let mut command = Command::new("ls");
1327 /// if let Ok(mut child) = command.spawn() {
1328 /// child.wait().expect("command wasn't running");
1329 /// println!("Child has finished its execution!");
1331 /// println!("ls command didn't start");
1334 #[stable(feature = "process", since = "1.0.0")]
1335 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1336 drop(self.stdin.take());
1337 self.handle.wait().map(ExitStatus)
1340 /// Attempts to collect the exit status of the child if it has already
1343 /// This function will not block the calling thread and will only
1344 /// check to see if the child process has exited or not. If the child has
1345 /// exited then on Unix the process id is reaped. This function is
1346 /// guaranteed to repeatedly return a successful exit status so long as the
1347 /// child has already exited.
1349 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1350 /// exit status is not available at this time then `Ok(None)` is returned.
1351 /// If an error occurs, then that error is returned.
1353 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1360 /// use std::process::Command;
1362 /// let mut child = Command::new("ls").spawn().unwrap();
1364 /// match child.try_wait() {
1365 /// Ok(Some(status)) => println!("exited with: {}", status),
1367 /// println!("status not ready yet, let's really wait");
1368 /// let res = child.wait();
1369 /// println!("result: {:?}", res);
1371 /// Err(e) => println!("error attempting to wait: {}", e),
1374 #[stable(feature = "process_try_wait", since = "1.18.0")]
1375 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1376 Ok(self.handle.try_wait()?.map(ExitStatus))
1379 /// Simultaneously waits for the child to exit and collect all remaining
1380 /// output on the stdout/stderr handles, returning an `Output`
1383 /// The stdin handle to the child process, if any, will be closed
1384 /// before waiting. This helps avoid deadlock: it ensures that the
1385 /// child does not block waiting for input from the parent, while
1386 /// the parent waits for the child to exit.
1388 /// By default, stdin, stdout and stderr are inherited from the parent.
1389 /// In order to capture the output into this `Result<Output>` it is
1390 /// necessary to create new pipes between parent and child. Use
1391 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1396 /// use std::process::{Command, Stdio};
1398 /// let child = Command::new("/bin/cat")
1399 /// .arg("file.txt")
1400 /// .stdout(Stdio::piped())
1402 /// .expect("failed to execute child");
1404 /// let output = child
1405 /// .wait_with_output()
1406 /// .expect("failed to wait on child");
1408 /// assert!(output.status.success());
1411 #[stable(feature = "process", since = "1.0.0")]
1412 pub fn wait_with_output(mut self) -> io::Result<Output> {
1413 drop(self.stdin.take());
1415 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1416 match (self.stdout.take(), self.stderr.take()) {
1418 (Some(mut out), None) => {
1419 let res = out.read_to_end(&mut stdout);
1422 (None, Some(mut err)) => {
1423 let res = err.read_to_end(&mut stderr);
1426 (Some(out), Some(err)) => {
1427 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1432 let status = self.wait()?;
1441 /// Terminates the current process with the specified exit code.
1443 /// This function will never return and will immediately terminate the current
1444 /// process. The exit code is passed through to the underlying OS and will be
1445 /// available for consumption by another process.
1447 /// Note that because this function never returns, and that it terminates the
1448 /// process, no destructors on the current stack or any other thread's stack
1449 /// will be run. If a clean shutdown is needed it is recommended to only call
1450 /// this function at a known point where there are no more destructors left
1453 /// ## Platform-specific behavior
1455 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1456 /// will be visible to a parent process inspecting the exit code. On most
1457 /// Unix-like platforms, only the eight least-significant bits are considered.
1461 /// Due to this function’s behavior regarding destructors, a conventional way
1462 /// to use the function is to extract the actual computation to another
1463 /// function and compute the exit code from its return value:
1466 /// fn run_app() -> Result<(), ()> {
1467 /// // Application logic here
1472 /// ::std::process::exit(match run_app() {
1475 /// eprintln!("error: {:?}", err);
1482 /// Due to [platform-specific behavior], the exit code for this example will be
1483 /// `0` on Linux, but `256` on Windows:
1486 /// use std::process;
1488 /// process::exit(0x0100);
1491 /// [platform-specific behavior]: #platform-specific-behavior
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 pub fn exit(code: i32) -> ! {
1494 ::sys_common::cleanup();
1495 ::sys::os::exit(code)
1498 /// Terminates the process in an abnormal fashion.
1500 /// The function will never return and will immediately terminate the current
1501 /// process in a platform specific "abnormal" manner.
1503 /// Note that because this function never returns, and that it terminates the
1504 /// process, no destructors on the current stack or any other thread's stack
1507 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1508 /// the current thread's stack and calls all destructors.
1509 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1510 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1511 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1513 /// If a clean shutdown is needed it is recommended to only call
1514 /// this function at a known point where there are no more destructors left
1520 /// use std::process;
1523 /// println!("aborting");
1525 /// process::abort();
1527 /// // execution never gets here
1531 /// The `abort` function terminates the process, so the destructor will not
1532 /// get run on the example below:
1535 /// use std::process;
1539 /// impl Drop for HasDrop {
1540 /// fn drop(&mut self) {
1541 /// println!("This will never be printed!");
1546 /// let _x = HasDrop;
1547 /// process::abort();
1548 /// // the destructor implemented for HasDrop will never get run
1552 /// [`panic!`]: ../../std/macro.panic.html
1553 /// [panic hook]: ../../std/panic/fn.set_hook.html
1554 #[stable(feature = "process_abort", since = "1.17.0")]
1555 pub fn abort() -> ! {
1556 unsafe { ::sys::abort_internal() };
1559 /// Returns the OS-assigned process identifier associated with this process.
1566 /// use std::process;
1568 /// println!("My pid is {}", process::id());
1572 #[stable(feature = "getpid", since = "1.26.0")]
1573 pub fn id() -> u32 {
1577 /// A trait for implementing arbitrary return types in the `main` function.
1579 /// The c-main function only supports to return integers as return type.
1580 /// So, every type implementing the `Termination` trait has to be converted
1583 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1584 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1585 #[cfg_attr(not(test), lang = "termination")]
1586 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1587 #[rustc_on_unimplemented(
1588 message="`main` has invalid return type `{Self}`",
1589 label="`main` can only return types that implement `{Termination}`")]
1590 pub trait Termination {
1591 /// Is called to get the representation of the value as status code.
1592 /// This status code is returned to the operating system.
1593 fn report(self) -> i32;
1596 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1597 impl Termination for () {
1599 fn report(self) -> i32 { ExitCode::SUCCESS.report() }
1602 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1603 impl<E: fmt::Debug> Termination for Result<(), E> {
1604 fn report(self) -> i32 {
1606 Ok(()) => ().report(),
1607 Err(err) => Err::<!, _>(err).report(),
1612 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1613 impl Termination for ! {
1614 fn report(self) -> i32 { self }
1617 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1618 impl<E: fmt::Debug> Termination for Result<!, E> {
1619 fn report(self) -> i32 {
1620 let Err(err) = self;
1621 eprintln!("Error: {:?}", err);
1622 ExitCode::FAILURE.report()
1626 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1627 impl Termination for ExitCode {
1629 fn report(self) -> i32 {
1634 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
1640 use super::{Command, Output, Stdio};
1642 // FIXME(#10380) these tests should not all be ignored on android.
1645 #[cfg_attr(target_os = "android", ignore)]
1647 let p = if cfg!(target_os = "windows") {
1648 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1650 Command::new("true").spawn()
1653 let mut p = p.unwrap();
1654 assert!(p.wait().unwrap().success());
1658 #[cfg_attr(target_os = "android", ignore)]
1659 fn smoke_failure() {
1660 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1667 #[cfg_attr(target_os = "android", ignore)]
1668 fn exit_reported_right() {
1669 let p = if cfg!(target_os = "windows") {
1670 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1672 Command::new("false").spawn()
1675 let mut p = p.unwrap();
1676 assert!(p.wait().unwrap().code() == Some(1));
1682 #[cfg_attr(target_os = "android", ignore)]
1683 fn signal_reported_right() {
1684 use os::unix::process::ExitStatusExt;
1686 let mut p = Command::new("/bin/sh")
1687 .arg("-c").arg("read a")
1688 .stdin(Stdio::piped())
1691 match p.wait().unwrap().signal() {
1693 result => panic!("not terminated by signal 9 (instead, {:?})",
1698 pub fn run_output(mut cmd: Command) -> String {
1699 let p = cmd.spawn();
1701 let mut p = p.unwrap();
1702 assert!(p.stdout.is_some());
1703 let mut ret = String::new();
1704 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1705 assert!(p.wait().unwrap().success());
1710 #[cfg_attr(target_os = "android", ignore)]
1712 if cfg!(target_os = "windows") {
1713 let mut cmd = Command::new("cmd");
1714 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1715 assert_eq!(run_output(cmd), "foobar\r\n");
1717 let mut cmd = Command::new("echo");
1718 cmd.arg("foobar").stdout(Stdio::piped());
1719 assert_eq!(run_output(cmd), "foobar\n");
1724 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1725 fn set_current_dir_works() {
1726 let mut cmd = Command::new("/bin/sh");
1727 cmd.arg("-c").arg("pwd")
1729 .stdout(Stdio::piped());
1730 assert_eq!(run_output(cmd), "/\n");
1734 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1736 let mut p = Command::new("/bin/sh")
1737 .arg("-c").arg("read line; echo $line")
1738 .stdin(Stdio::piped())
1739 .stdout(Stdio::piped())
1741 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1742 drop(p.stdin.take());
1743 let mut out = String::new();
1744 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1745 assert!(p.wait().unwrap().success());
1746 assert_eq!(out, "foobar\n");
1751 #[cfg_attr(target_os = "android", ignore)]
1754 use os::unix::prelude::*;
1756 let mut p = Command::new("/bin/sh")
1757 .arg("-c").arg("true")
1758 .uid(unsafe { libc::getuid() })
1759 .gid(unsafe { libc::getgid() })
1761 assert!(p.wait().unwrap().success());
1765 #[cfg_attr(target_os = "android", ignore)]
1767 fn uid_to_root_fails() {
1768 use os::unix::prelude::*;
1771 // if we're already root, this isn't a valid test. Most of the bots run
1772 // as non-root though (android is an exception).
1773 if unsafe { libc::getuid() == 0 } { return }
1774 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1778 #[cfg_attr(target_os = "android", ignore)]
1779 fn test_process_status() {
1780 let mut status = if cfg!(target_os = "windows") {
1781 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1783 Command::new("false").status().unwrap()
1785 assert!(status.code() == Some(1));
1787 status = if cfg!(target_os = "windows") {
1788 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1790 Command::new("true").status().unwrap()
1792 assert!(status.success());
1796 fn test_process_output_fail_to_start() {
1797 match Command::new("/no-binary-by-this-name-should-exist").output() {
1798 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1804 #[cfg_attr(target_os = "android", ignore)]
1805 fn test_process_output_output() {
1806 let Output {status, stdout, stderr}
1807 = if cfg!(target_os = "windows") {
1808 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1810 Command::new("echo").arg("hello").output().unwrap()
1812 let output_str = str::from_utf8(&stdout).unwrap();
1814 assert!(status.success());
1815 assert_eq!(output_str.trim().to_string(), "hello");
1816 assert_eq!(stderr, Vec::new());
1820 #[cfg_attr(target_os = "android", ignore)]
1821 fn test_process_output_error() {
1822 let Output {status, stdout, stderr}
1823 = if cfg!(target_os = "windows") {
1824 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1826 Command::new("mkdir").arg("./").output().unwrap()
1829 assert!(status.code() == Some(1));
1830 assert_eq!(stdout, Vec::new());
1831 assert!(!stderr.is_empty());
1835 #[cfg_attr(target_os = "android", ignore)]
1836 fn test_finish_once() {
1837 let mut prog = if cfg!(target_os = "windows") {
1838 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1840 Command::new("false").spawn().unwrap()
1842 assert!(prog.wait().unwrap().code() == Some(1));
1846 #[cfg_attr(target_os = "android", ignore)]
1847 fn test_finish_twice() {
1848 let mut prog = if cfg!(target_os = "windows") {
1849 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1851 Command::new("false").spawn().unwrap()
1853 assert!(prog.wait().unwrap().code() == Some(1));
1854 assert!(prog.wait().unwrap().code() == Some(1));
1858 #[cfg_attr(target_os = "android", ignore)]
1859 fn test_wait_with_output_once() {
1860 let prog = if cfg!(target_os = "windows") {
1861 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1863 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1866 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1867 let output_str = str::from_utf8(&stdout).unwrap();
1869 assert!(status.success());
1870 assert_eq!(output_str.trim().to_string(), "hello");
1871 assert_eq!(stderr, Vec::new());
1874 #[cfg(all(unix, not(target_os="android")))]
1875 pub fn env_cmd() -> Command {
1878 #[cfg(target_os="android")]
1879 pub fn env_cmd() -> Command {
1880 let mut cmd = Command::new("/system/bin/sh");
1881 cmd.arg("-c").arg("set");
1886 pub fn env_cmd() -> Command {
1887 let mut cmd = Command::new("cmd");
1888 cmd.arg("/c").arg("set");
1893 fn test_override_env() {
1896 // In some build environments (such as chrooted Nix builds), `env` can
1897 // only be found in the explicitly-provided PATH env variable, not in
1898 // default places such as /bin or /usr/bin. So we need to pass through
1899 // PATH to our sub-process.
1900 let mut cmd = env_cmd();
1901 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1902 if let Some(p) = env::var_os("PATH") {
1903 cmd.env("PATH", &p);
1905 let result = cmd.output().unwrap();
1906 let output = String::from_utf8_lossy(&result.stdout).to_string();
1908 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1909 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1913 fn test_add_to_env() {
1914 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1915 let output = String::from_utf8_lossy(&result.stdout).to_string();
1917 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1918 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1922 fn test_capture_env_at_spawn() {
1925 let mut cmd = env_cmd();
1926 cmd.env("RUN_TEST_NEW_ENV1", "123");
1928 // This variable will not be present if the environment has already
1929 // been captured above.
1930 env::set_var("RUN_TEST_NEW_ENV2", "456");
1931 let result = cmd.output().unwrap();
1932 env::remove_var("RUN_TEST_NEW_ENV2");
1934 let output = String::from_utf8_lossy(&result.stdout).to_string();
1936 assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1937 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1938 assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1939 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1942 // Regression tests for #30858.
1944 fn test_interior_nul_in_progname_is_error() {
1945 match Command::new("has-some-\0\0s-inside").spawn() {
1946 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1952 fn test_interior_nul_in_arg_is_error() {
1953 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1954 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1960 fn test_interior_nul_in_args_is_error() {
1961 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1962 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1968 fn test_interior_nul_in_current_dir_is_error() {
1969 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1970 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1975 // Regression tests for #30862.
1977 fn test_interior_nul_in_env_key_is_error() {
1978 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1979 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1985 fn test_interior_nul_in_env_value_is_error() {
1986 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1987 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1992 /// Test that process creation flags work by debugging a process.
1993 /// Other creation flags make it hard or impossible to detect
1994 /// behavioral changes in the process.
1997 fn test_creation_flags() {
1998 use os::windows::process::CommandExt;
1999 use sys::c::{BOOL, DWORD, INFINITE};
2001 struct DEBUG_EVENT {
2002 pub event_code: DWORD,
2003 pub process_id: DWORD,
2004 pub thread_id: DWORD,
2005 // This is a union in the real struct, but we don't
2006 // need this data for the purposes of this test.
2007 pub _junk: [u8; 164],
2011 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
2012 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
2013 dwContinueStatus: DWORD) -> BOOL;
2016 const DEBUG_PROCESS: DWORD = 1;
2017 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
2018 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
2020 let mut child = Command::new("cmd")
2021 .creation_flags(DEBUG_PROCESS)
2022 .stdin(Stdio::piped()).spawn().unwrap();
2023 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
2025 let mut event = DEBUG_EVENT {
2032 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
2033 panic!("WaitForDebugEvent failed!");
2037 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
2041 if unsafe { ContinueDebugEvent(event.process_id,
2043 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
2044 panic!("ContinueDebugEvent failed!");
2047 assert!(events > 0);
2051 fn test_command_implements_send() {
2052 fn take_send_type<T: Send>(_: T) {}
2053 take_send_type(Command::new(""))