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.
15 //! Basic usage where we try to execute the `cat` shell command:
18 //! use std::process::Command;
20 //! let mut child = Command::new("/bin/cat")
23 //! .expect("failed to execute child");
25 //! let ecode = child.wait()
26 //! .expect("failed to wait on child");
28 //! assert!(ecode.success());
31 //! Calling a command with input and reading its output:
34 //! use std::process::{Command, Stdio};
35 //! use std::io::Write;
37 //! let mut child = Command::new("/bin/cat")
38 //! .stdin(Stdio::piped())
39 //! .stdout(Stdio::piped())
41 //! .expect("failed to execute child");
44 //! // limited borrow of stdin
45 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
46 //! stdin.write_all(b"test").expect("failed to write to stdin");
49 //! let output = child
50 //! .wait_with_output()
51 //! .expect("failed to wait on child");
53 //! assert_eq!(b"test", output.stdout.as_slice());
56 #![stable(feature = "process", since = "1.0.0")]
63 use io::{self, Initializer};
66 use sys::pipe::{read2, AnonPipe};
67 use sys::process as imp;
68 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
70 /// Representation of a running or exited child process.
72 /// This structure is used to represent and manage child processes. A child
73 /// process is created via the [`Command`] struct, which configures the
74 /// spawning process and can itself be constructed using a builder-style
77 /// There is no implementation of [`Drop`] for child processes,
78 /// so if you do not ensure the `Child` has exited then it will continue to
79 /// run, even after the `Child` handle to the child process has gone out of
82 /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
83 /// the parent process wait until the child has actually exited before
89 /// use std::process::Command;
91 /// let mut child = Command::new("/bin/cat")
94 /// .expect("failed to execute child");
96 /// let ecode = child.wait()
97 /// .expect("failed to wait on child");
99 /// assert!(ecode.success());
102 /// [`Command`]: struct.Command.html
103 /// [`Drop`]: ../../core/ops/trait.Drop.html
104 /// [`wait`]: #method.wait
105 #[stable(feature = "process", since = "1.0.0")]
107 handle: imp::Process,
109 /// The handle for writing to the child's standard input (stdin), if it has
111 #[stable(feature = "process", since = "1.0.0")]
112 pub stdin: Option<ChildStdin>,
114 /// The handle for reading from the child's standard output (stdout), if it
115 /// has been captured.
116 #[stable(feature = "process", since = "1.0.0")]
117 pub stdout: Option<ChildStdout>,
119 /// The handle for reading from the child's standard error (stderr), if it
120 /// has been captured.
121 #[stable(feature = "process", since = "1.0.0")]
122 pub stderr: Option<ChildStderr>,
125 impl AsInner<imp::Process> for Child {
126 fn as_inner(&self) -> &imp::Process { &self.handle }
129 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
130 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
133 stdin: io.stdin.map(ChildStdin::from_inner),
134 stdout: io.stdout.map(ChildStdout::from_inner),
135 stderr: io.stderr.map(ChildStderr::from_inner),
140 impl IntoInner<imp::Process> for Child {
141 fn into_inner(self) -> imp::Process { self.handle }
144 #[stable(feature = "std_debug", since = "1.16.0")]
145 impl fmt::Debug for Child {
146 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147 f.debug_struct("Child")
148 .field("stdin", &self.stdin)
149 .field("stdout", &self.stdout)
150 .field("stderr", &self.stderr)
155 /// A handle to a child process's standard input (stdin).
157 /// This struct is used in the [`stdin`] field on [`Child`].
159 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
160 /// file handle will be closed. If the child process was blocked on input prior
161 /// to being dropped, it will become unblocked after dropping.
163 /// [`Child`]: struct.Child.html
164 /// [`stdin`]: struct.Child.html#structfield.stdin
165 /// [dropped]: ../ops/trait.Drop.html
166 #[stable(feature = "process", since = "1.0.0")]
167 pub struct ChildStdin {
171 #[stable(feature = "process", since = "1.0.0")]
172 impl Write for ChildStdin {
173 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
174 self.inner.write(buf)
177 fn flush(&mut self) -> io::Result<()> {
182 impl AsInner<AnonPipe> for ChildStdin {
183 fn as_inner(&self) -> &AnonPipe { &self.inner }
186 impl IntoInner<AnonPipe> for ChildStdin {
187 fn into_inner(self) -> AnonPipe { self.inner }
190 impl FromInner<AnonPipe> for ChildStdin {
191 fn from_inner(pipe: AnonPipe) -> ChildStdin {
192 ChildStdin { inner: pipe }
196 #[stable(feature = "std_debug", since = "1.16.0")]
197 impl fmt::Debug for ChildStdin {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 f.pad("ChildStdin { .. }")
203 /// A handle to a child process's standard output (stdout).
205 /// This struct is used in the [`stdout`] field on [`Child`].
207 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
208 /// underlying file handle will be closed.
210 /// [`Child`]: struct.Child.html
211 /// [`stdout`]: struct.Child.html#structfield.stdout
212 /// [dropped]: ../ops/trait.Drop.html
213 #[stable(feature = "process", since = "1.0.0")]
214 pub struct ChildStdout {
218 #[stable(feature = "process", since = "1.0.0")]
219 impl Read for ChildStdout {
220 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
224 unsafe fn initializer(&self) -> Initializer {
229 impl AsInner<AnonPipe> for ChildStdout {
230 fn as_inner(&self) -> &AnonPipe { &self.inner }
233 impl IntoInner<AnonPipe> for ChildStdout {
234 fn into_inner(self) -> AnonPipe { self.inner }
237 impl FromInner<AnonPipe> for ChildStdout {
238 fn from_inner(pipe: AnonPipe) -> ChildStdout {
239 ChildStdout { inner: pipe }
243 #[stable(feature = "std_debug", since = "1.16.0")]
244 impl fmt::Debug for ChildStdout {
245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
246 f.pad("ChildStdout { .. }")
250 /// A handle to a child process's stderr.
252 /// This struct is used in the [`stderr`] field on [`Child`].
254 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
255 /// underlying file handle will be closed.
257 /// [`Child`]: struct.Child.html
258 /// [`stderr`]: struct.Child.html#structfield.stderr
259 /// [dropped]: ../ops/trait.Drop.html
260 #[stable(feature = "process", since = "1.0.0")]
261 pub struct ChildStderr {
265 #[stable(feature = "process", since = "1.0.0")]
266 impl Read for ChildStderr {
267 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
271 unsafe fn initializer(&self) -> Initializer {
276 impl AsInner<AnonPipe> for ChildStderr {
277 fn as_inner(&self) -> &AnonPipe { &self.inner }
280 impl IntoInner<AnonPipe> for ChildStderr {
281 fn into_inner(self) -> AnonPipe { self.inner }
284 impl FromInner<AnonPipe> for ChildStderr {
285 fn from_inner(pipe: AnonPipe) -> ChildStderr {
286 ChildStderr { inner: pipe }
290 #[stable(feature = "std_debug", since = "1.16.0")]
291 impl fmt::Debug for ChildStderr {
292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293 f.pad("ChildStderr { .. }")
297 /// A process builder, providing fine-grained control
298 /// over how a new process should be spawned.
300 /// A default configuration can be
301 /// generated using `Command::new(program)`, where `program` gives a path to the
302 /// program to be executed. Additional builder methods allow the configuration
303 /// to be changed (for example, by adding arguments) prior to spawning:
306 /// use std::process::Command;
308 /// let output = if cfg!(target_os = "windows") {
309 /// Command::new("cmd")
310 /// .args(&["/C", "echo hello"])
312 /// .expect("failed to execute process")
314 /// Command::new("sh")
316 /// .arg("echo hello")
318 /// .expect("failed to execute process")
321 /// let hello = output.stdout;
323 #[stable(feature = "process", since = "1.0.0")]
329 /// Constructs a new `Command` for launching the program at
330 /// path `program`, with the following default configuration:
332 /// * No arguments to the program
333 /// * Inherit the current process's environment
334 /// * Inherit the current process's working directory
335 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
337 /// Builder methods are provided to change these defaults and
338 /// otherwise configure the process.
340 /// If `program` is not an absolute path, the `PATH` will be searched in
341 /// an OS-defined way.
343 /// The search path to be used may be controlled by setting the
344 /// `PATH` environment variable on the Command,
345 /// but this has some implementation limitations on Windows
346 /// (see https://github.com/rust-lang/rust/issues/37519).
353 /// use std::process::Command;
355 /// Command::new("sh")
357 /// .expect("sh command failed to start");
359 #[stable(feature = "process", since = "1.0.0")]
360 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
361 Command { inner: imp::Command::new(program.as_ref()) }
364 /// Add an argument to pass to the program.
366 /// Only one argument can be passed per use. So instead of:
369 /// # std::process::Command::new("sh")
370 /// .arg("-C /path/to/repo")
377 /// # std::process::Command::new("sh")
379 /// .arg("/path/to/repo")
383 /// To pass multiple arguments see [`args`].
385 /// [`args`]: #method.args
392 /// use std::process::Command;
394 /// Command::new("ls")
398 /// .expect("ls command failed to start");
400 #[stable(feature = "process", since = "1.0.0")]
401 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
402 self.inner.arg(arg.as_ref());
406 /// Add multiple arguments to pass to the program.
408 /// To pass a single argument see [`arg`].
410 /// [`arg`]: #method.arg
417 /// use std::process::Command;
419 /// Command::new("ls")
420 /// .args(&["-l", "-a"])
422 /// .expect("ls command failed to start");
424 #[stable(feature = "process", since = "1.0.0")]
425 pub fn args<I, S>(&mut self, args: I) -> &mut Command
426 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
429 self.arg(arg.as_ref());
434 /// Inserts or updates an environment variable mapping.
436 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
437 /// and case-sensitive on all other platforms.
444 /// use std::process::Command;
446 /// Command::new("ls")
447 /// .env("PATH", "/bin")
449 /// .expect("ls command failed to start");
451 #[stable(feature = "process", since = "1.0.0")]
452 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
453 where K: AsRef<OsStr>, V: AsRef<OsStr>
455 self.inner.env(key.as_ref(), val.as_ref());
459 /// Add or update multiple environment variable mappings.
466 /// use std::process::{Command, Stdio};
468 /// use std::collections::HashMap;
470 /// let filtered_env : HashMap<String, String> =
471 /// env::vars().filter(|&(ref k, _)|
472 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
475 /// Command::new("printenv")
476 /// .stdin(Stdio::null())
477 /// .stdout(Stdio::inherit())
479 /// .envs(&filtered_env)
481 /// .expect("printenv failed to start");
483 #[stable(feature = "command_envs", since = "1.19.0")]
484 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
485 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
487 for (ref key, ref val) in vars {
488 self.inner.env(key.as_ref(), val.as_ref());
493 /// Removes an environment variable mapping.
500 /// use std::process::Command;
502 /// Command::new("ls")
503 /// .env_remove("PATH")
505 /// .expect("ls command failed to start");
507 #[stable(feature = "process", since = "1.0.0")]
508 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
509 self.inner.env_remove(key.as_ref());
513 /// Clears the entire environment map for the child process.
520 /// use std::process::Command;
522 /// Command::new("ls")
525 /// .expect("ls command failed to start");
527 #[stable(feature = "process", since = "1.0.0")]
528 pub fn env_clear(&mut self) -> &mut Command {
529 self.inner.env_clear();
533 /// Sets the working directory for the child process.
540 /// use std::process::Command;
542 /// Command::new("ls")
543 /// .current_dir("/bin")
545 /// .expect("ls command failed to start");
547 #[stable(feature = "process", since = "1.0.0")]
548 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
549 self.inner.cwd(dir.as_ref().as_ref());
553 /// Configuration for the child process's standard input (stdin) handle.
560 /// use std::process::{Command, Stdio};
562 /// Command::new("ls")
563 /// .stdin(Stdio::null())
565 /// .expect("ls command failed to start");
567 #[stable(feature = "process", since = "1.0.0")]
568 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
569 self.inner.stdin(cfg.into().0);
573 /// Configuration for the child process's standard output (stdout) handle.
580 /// use std::process::{Command, Stdio};
582 /// Command::new("ls")
583 /// .stdout(Stdio::null())
585 /// .expect("ls command failed to start");
587 #[stable(feature = "process", since = "1.0.0")]
588 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
589 self.inner.stdout(cfg.into().0);
593 /// Configuration for the child process's standard error (stderr) handle.
600 /// use std::process::{Command, Stdio};
602 /// Command::new("ls")
603 /// .stderr(Stdio::null())
605 /// .expect("ls command failed to start");
607 #[stable(feature = "process", since = "1.0.0")]
608 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
609 self.inner.stderr(cfg.into().0);
613 /// Executes the command as a child process, returning a handle to it.
615 /// By default, stdin, stdout and stderr are inherited from the parent.
622 /// use std::process::Command;
624 /// Command::new("ls")
626 /// .expect("ls command failed to start");
628 #[stable(feature = "process", since = "1.0.0")]
629 pub fn spawn(&mut self) -> io::Result<Child> {
630 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
633 /// Executes the command as a child process, waiting for it to finish and
634 /// collecting all of its output.
636 /// By default, stdin, stdout and stderr are captured (and used to
637 /// provide the resulting output).
642 /// use std::process::Command;
643 /// let output = Command::new("/bin/cat")
646 /// .expect("failed to execute process");
648 /// println!("status: {}", output.status);
649 /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
650 /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
652 /// assert!(output.status.success());
654 #[stable(feature = "process", since = "1.0.0")]
655 pub fn output(&mut self) -> io::Result<Output> {
656 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
657 .and_then(|p| p.wait_with_output())
660 /// Executes a command as a child process, waiting for it to finish and
661 /// collecting its exit status.
663 /// By default, stdin, stdout and stderr are inherited from the parent.
668 /// use std::process::Command;
670 /// let status = Command::new("/bin/cat")
673 /// .expect("failed to execute process");
675 /// println!("process exited with: {}", status);
677 /// assert!(status.success());
679 #[stable(feature = "process", since = "1.0.0")]
680 pub fn status(&mut self) -> io::Result<ExitStatus> {
681 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
682 .and_then(|mut p| p.wait())
686 #[stable(feature = "rust1", since = "1.0.0")]
687 impl fmt::Debug for Command {
688 /// Format the program and arguments of a Command for display. Any
689 /// non-utf8 data is lossily converted using the utf8 replacement
691 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
696 impl AsInner<imp::Command> for Command {
697 fn as_inner(&self) -> &imp::Command { &self.inner }
700 impl AsInnerMut<imp::Command> for Command {
701 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
704 /// The output of a finished process.
706 /// This is returned in a Result by either the [`output`] method of a
707 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
710 /// [`Command`]: struct.Command.html
711 /// [`Child`]: struct.Child.html
712 /// [`output`]: struct.Command.html#method.output
713 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
714 #[derive(PartialEq, Eq, Clone)]
715 #[stable(feature = "process", since = "1.0.0")]
717 /// The status (exit code) of the process.
718 #[stable(feature = "process", since = "1.0.0")]
719 pub status: ExitStatus,
720 /// The data that the process wrote to stdout.
721 #[stable(feature = "process", since = "1.0.0")]
723 /// The data that the process wrote to stderr.
724 #[stable(feature = "process", since = "1.0.0")]
728 // If either stderr or stdout are valid utf8 strings it prints the valid
729 // strings, otherwise it prints the byte sequence instead
730 #[stable(feature = "process_output_debug", since = "1.7.0")]
731 impl fmt::Debug for Output {
732 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
734 let stdout_utf8 = str::from_utf8(&self.stdout);
735 let stdout_debug: &fmt::Debug = match stdout_utf8 {
737 Err(_) => &self.stdout
740 let stderr_utf8 = str::from_utf8(&self.stderr);
741 let stderr_debug: &fmt::Debug = match stderr_utf8 {
743 Err(_) => &self.stderr
746 fmt.debug_struct("Output")
747 .field("status", &self.status)
748 .field("stdout", stdout_debug)
749 .field("stderr", stderr_debug)
754 /// Describes what to do with a standard I/O stream for a child process when
755 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
757 /// [`stdin`]: struct.Command.html#method.stdin
758 /// [`stdout`]: struct.Command.html#method.stdout
759 /// [`stderr`]: struct.Command.html#method.stderr
760 /// [`Command`]: struct.Command.html
761 #[stable(feature = "process", since = "1.0.0")]
762 pub struct Stdio(imp::Stdio);
765 /// A new pipe should be arranged to connect the parent and child processes.
772 /// use std::process::{Command, Stdio};
774 /// let output = Command::new("echo")
775 /// .arg("Hello, world!")
776 /// .stdout(Stdio::piped())
778 /// .expect("Failed to execute command");
780 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
781 /// // Nothing echoed to console
787 /// use std::io::Write;
788 /// use std::process::{Command, Stdio};
790 /// let mut child = Command::new("rev")
791 /// .stdin(Stdio::piped())
792 /// .stdout(Stdio::piped())
794 /// .expect("Failed to spawn child process");
797 /// let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
798 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
801 /// let output = child.wait_with_output().expect("Failed to read stdout");
802 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
804 #[stable(feature = "process", since = "1.0.0")]
805 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
807 /// The child inherits from the corresponding parent descriptor.
814 /// use std::process::{Command, Stdio};
816 /// let output = Command::new("echo")
817 /// .arg("Hello, world!")
818 /// .stdout(Stdio::inherit())
820 /// .expect("Failed to execute command");
822 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
823 /// // "Hello, world!" echoed to console
829 /// use std::process::{Command, Stdio};
831 /// let output = Command::new("rev")
832 /// .stdin(Stdio::inherit())
833 /// .stdout(Stdio::piped())
835 /// .expect("Failed to execute command");
837 /// println!("You piped in the reverse of: {}", String::from_utf8_lossy(&output.stdout));
839 #[stable(feature = "process", since = "1.0.0")]
840 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
842 /// This stream will be ignored. This is the equivalent of attaching the
843 /// stream to `/dev/null`
850 /// use std::process::{Command, Stdio};
852 /// let output = Command::new("echo")
853 /// .arg("Hello, world!")
854 /// .stdout(Stdio::null())
856 /// .expect("Failed to execute command");
858 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
859 /// // Nothing echoed to console
865 /// use std::process::{Command, Stdio};
867 /// let output = Command::new("rev")
868 /// .stdin(Stdio::null())
869 /// .stdout(Stdio::piped())
871 /// .expect("Failed to execute command");
873 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
874 /// // Ignores any piped-in input
876 #[stable(feature = "process", since = "1.0.0")]
877 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
880 impl FromInner<imp::Stdio> for Stdio {
881 fn from_inner(inner: imp::Stdio) -> Stdio {
886 #[stable(feature = "std_debug", since = "1.16.0")]
887 impl fmt::Debug for Stdio {
888 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
889 f.pad("Stdio { .. }")
893 #[stable(feature = "stdio_from", since = "1.20.0")]
894 impl From<ChildStdin> for Stdio {
895 fn from(child: ChildStdin) -> Stdio {
896 Stdio::from_inner(child.into_inner().into())
900 #[stable(feature = "stdio_from", since = "1.20.0")]
901 impl From<ChildStdout> for Stdio {
902 fn from(child: ChildStdout) -> Stdio {
903 Stdio::from_inner(child.into_inner().into())
907 #[stable(feature = "stdio_from", since = "1.20.0")]
908 impl From<ChildStderr> for Stdio {
909 fn from(child: ChildStderr) -> Stdio {
910 Stdio::from_inner(child.into_inner().into())
914 #[stable(feature = "stdio_from", since = "1.20.0")]
915 impl From<fs::File> for Stdio {
916 fn from(file: fs::File) -> Stdio {
917 Stdio::from_inner(file.into_inner().into())
921 /// Describes the result of a process after it has terminated.
923 /// This `struct` is used to represent the exit status of a child process.
924 /// Child processes are created via the [`Command`] struct and their exit
925 /// status is exposed through the [`status`] method.
927 /// [`Command`]: struct.Command.html
928 /// [`status`]: struct.Command.html#method.status
929 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
930 #[stable(feature = "process", since = "1.0.0")]
931 pub struct ExitStatus(imp::ExitStatus);
934 /// Was termination successful? Signal termination is not considered a
935 /// success, and success is defined as a zero exit status.
940 /// use std::process::Command;
942 /// let status = Command::new("mkdir")
945 /// .expect("failed to execute mkdir");
947 /// if status.success() {
948 /// println!("'projects/' directory created");
950 /// println!("failed to create 'projects/' directory");
953 #[stable(feature = "process", since = "1.0.0")]
954 pub fn success(&self) -> bool {
958 /// Returns the exit code of the process, if any.
960 /// On Unix, this will return `None` if the process was terminated
961 /// by a signal; `std::os::unix` provides an extension trait for
962 /// extracting the signal and other details from the `ExitStatus`.
967 /// use std::process::Command;
969 /// let status = Command::new("mkdir")
972 /// .expect("failed to execute mkdir");
974 /// match status.code() {
975 /// Some(code) => println!("Exited with status code: {}", code),
976 /// None => println!("Process terminated by signal")
979 #[stable(feature = "process", since = "1.0.0")]
980 pub fn code(&self) -> Option<i32> {
985 impl AsInner<imp::ExitStatus> for ExitStatus {
986 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
989 impl FromInner<imp::ExitStatus> for ExitStatus {
990 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
995 #[stable(feature = "process", since = "1.0.0")]
996 impl fmt::Display for ExitStatus {
997 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1003 /// Forces the child to exit. This is equivalent to sending a
1004 /// SIGKILL on unix platforms.
1011 /// use std::process::Command;
1013 /// let mut command = Command::new("yes");
1014 /// if let Ok(mut child) = command.spawn() {
1015 /// child.kill().expect("command wasn't running");
1017 /// println!("yes command didn't start");
1020 #[stable(feature = "process", since = "1.0.0")]
1021 pub fn kill(&mut self) -> io::Result<()> {
1025 /// Returns the OS-assigned process identifier associated with this child.
1032 /// use std::process::Command;
1034 /// let mut command = Command::new("ls");
1035 /// if let Ok(child) = command.spawn() {
1036 /// println!("Child's id is {}", child.id());
1038 /// println!("ls command didn't start");
1041 #[stable(feature = "process_id", since = "1.3.0")]
1042 pub fn id(&self) -> u32 {
1046 /// Waits for the child to exit completely, returning the status that it
1047 /// exited with. This function will continue to have the same return value
1048 /// after it has been called at least once.
1050 /// The stdin handle to the child process, if any, will be closed
1051 /// before waiting. This helps avoid deadlock: it ensures that the
1052 /// child does not block waiting for input from the parent, while
1053 /// the parent waits for the child to exit.
1060 /// use std::process::Command;
1062 /// let mut command = Command::new("ls");
1063 /// if let Ok(mut child) = command.spawn() {
1064 /// child.wait().expect("command wasn't running");
1065 /// println!("Child has finished its execution!");
1067 /// println!("ls command didn't start");
1070 #[stable(feature = "process", since = "1.0.0")]
1071 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1072 drop(self.stdin.take());
1073 self.handle.wait().map(ExitStatus)
1076 /// Attempts to collect the exit status of the child if it has already
1079 /// This function will not block the calling thread and will only advisorily
1080 /// check to see if the child process has exited or not. If the child has
1081 /// exited then on Unix the process id is reaped. This function is
1082 /// guaranteed to repeatedly return a successful exit status so long as the
1083 /// child has already exited.
1085 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1086 /// exit status is not available at this time then `Ok(None)` is returned.
1087 /// If an error occurs, then that error is returned.
1089 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1096 /// use std::process::Command;
1098 /// let mut child = Command::new("ls").spawn().unwrap();
1100 /// match child.try_wait() {
1101 /// Ok(Some(status)) => println!("exited with: {}", status),
1103 /// println!("status not ready yet, let's really wait");
1104 /// let res = child.wait();
1105 /// println!("result: {:?}", res);
1107 /// Err(e) => println!("error attempting to wait: {}", e),
1110 #[stable(feature = "process_try_wait", since = "1.18.0")]
1111 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1112 Ok(self.handle.try_wait()?.map(ExitStatus))
1115 /// Simultaneously waits for the child to exit and collect all remaining
1116 /// output on the stdout/stderr handles, returning an `Output`
1119 /// The stdin handle to the child process, if any, will be closed
1120 /// before waiting. This helps avoid deadlock: it ensures that the
1121 /// child does not block waiting for input from the parent, while
1122 /// the parent waits for the child to exit.
1124 /// By default, stdin, stdout and stderr are inherited from the parent.
1125 /// In order to capture the output into this `Result<Output>` it is
1126 /// necessary to create new pipes between parent and child. Use
1127 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1132 /// use std::process::{Command, Stdio};
1134 /// let child = Command::new("/bin/cat")
1135 /// .arg("file.txt")
1136 /// .stdout(Stdio::piped())
1138 /// .expect("failed to execute child");
1140 /// let output = child
1141 /// .wait_with_output()
1142 /// .expect("failed to wait on child");
1144 /// assert!(output.status.success());
1147 #[stable(feature = "process", since = "1.0.0")]
1148 pub fn wait_with_output(mut self) -> io::Result<Output> {
1149 drop(self.stdin.take());
1151 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1152 match (self.stdout.take(), self.stderr.take()) {
1154 (Some(mut out), None) => {
1155 let res = out.read_to_end(&mut stdout);
1158 (None, Some(mut err)) => {
1159 let res = err.read_to_end(&mut stderr);
1162 (Some(out), Some(err)) => {
1163 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1168 let status = self.wait()?;
1177 /// Terminates the current process with the specified exit code.
1179 /// This function will never return and will immediately terminate the current
1180 /// process. The exit code is passed through to the underlying OS and will be
1181 /// available for consumption by another process.
1183 /// Note that because this function never returns, and that it terminates the
1184 /// process, no destructors on the current stack or any other thread's stack
1185 /// will be run. If a clean shutdown is needed it is recommended to only call
1186 /// this function at a known point where there are no more destructors left
1189 /// ## Platform-specific behavior
1191 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1192 /// will be visible to a parent process inspecting the exit code. On most
1193 /// Unix-like platforms, only the eight least-significant bits are considered.
1197 /// Due to this function’s behavior regarding destructors, a conventional way
1198 /// to use the function is to extract the actual computation to another
1199 /// function and compute the exit code from its return value:
1202 /// fn run_app() -> Result<(), ()> {
1203 /// // Application logic here
1208 /// ::std::process::exit(match run_app() {
1211 /// eprintln!("error: {:?}", err);
1218 /// Due to [platform-specific behavior], the exit code for this example will be
1219 /// `0` on Linux, but `256` on Windows:
1222 /// use std::process;
1224 /// process::exit(0x0100);
1227 /// [platform-specific behavior]: #platform-specific-behavior
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub fn exit(code: i32) -> ! {
1230 ::sys_common::cleanup();
1231 ::sys::os::exit(code)
1234 /// Terminates the process in an abnormal fashion.
1236 /// The function will never return and will immediately terminate the current
1237 /// process in a platform specific "abnormal" manner.
1239 /// Note that because this function never returns, and that it terminates the
1240 /// process, no destructors on the current stack or any other thread's stack
1243 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1244 /// the current thread's stack and calls all destructors.
1245 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1246 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1247 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1249 /// If a clean shutdown is needed it is recommended to only call
1250 /// this function at a known point where there are no more destructors left
1256 /// use std::process;
1259 /// println!("aborting");
1261 /// process::abort();
1263 /// // execution never gets here
1267 /// The `abort` function terminates the process, so the destructor will not
1268 /// get run on the example below:
1271 /// use std::process;
1275 /// impl Drop for HasDrop {
1276 /// fn drop(&mut self) {
1277 /// println!("This will never be printed!");
1282 /// let _x = HasDrop;
1283 /// process::abort();
1284 /// // the destructor implemented for HasDrop will never get run
1288 /// [`panic!`]: ../../std/macro.panic.html
1289 /// [panic hook]: ../../std/panic/fn.set_hook.html
1290 #[stable(feature = "process_abort", since = "1.17.0")]
1291 pub fn abort() -> ! {
1292 unsafe { ::sys::abort_internal() };
1295 #[cfg(all(test, not(target_os = "emscripten")))]
1301 use super::{Command, Output, Stdio};
1303 // FIXME(#10380) these tests should not all be ignored on android.
1306 #[cfg_attr(target_os = "android", ignore)]
1308 let p = if cfg!(target_os = "windows") {
1309 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1311 Command::new("true").spawn()
1314 let mut p = p.unwrap();
1315 assert!(p.wait().unwrap().success());
1319 #[cfg_attr(target_os = "android", ignore)]
1320 fn smoke_failure() {
1321 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1328 #[cfg_attr(target_os = "android", ignore)]
1329 fn exit_reported_right() {
1330 let p = if cfg!(target_os = "windows") {
1331 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1333 Command::new("false").spawn()
1336 let mut p = p.unwrap();
1337 assert!(p.wait().unwrap().code() == Some(1));
1343 #[cfg_attr(target_os = "android", ignore)]
1344 fn signal_reported_right() {
1345 use os::unix::process::ExitStatusExt;
1347 let mut p = Command::new("/bin/sh")
1348 .arg("-c").arg("read a")
1349 .stdin(Stdio::piped())
1352 match p.wait().unwrap().signal() {
1354 result => panic!("not terminated by signal 9 (instead, {:?})",
1359 pub fn run_output(mut cmd: Command) -> String {
1360 let p = cmd.spawn();
1362 let mut p = p.unwrap();
1363 assert!(p.stdout.is_some());
1364 let mut ret = String::new();
1365 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1366 assert!(p.wait().unwrap().success());
1371 #[cfg_attr(target_os = "android", ignore)]
1373 if cfg!(target_os = "windows") {
1374 let mut cmd = Command::new("cmd");
1375 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1376 assert_eq!(run_output(cmd), "foobar\r\n");
1378 let mut cmd = Command::new("echo");
1379 cmd.arg("foobar").stdout(Stdio::piped());
1380 assert_eq!(run_output(cmd), "foobar\n");
1385 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1386 fn set_current_dir_works() {
1387 let mut cmd = Command::new("/bin/sh");
1388 cmd.arg("-c").arg("pwd")
1390 .stdout(Stdio::piped());
1391 assert_eq!(run_output(cmd), "/\n");
1395 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1397 let mut p = Command::new("/bin/sh")
1398 .arg("-c").arg("read line; echo $line")
1399 .stdin(Stdio::piped())
1400 .stdout(Stdio::piped())
1402 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1403 drop(p.stdin.take());
1404 let mut out = String::new();
1405 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1406 assert!(p.wait().unwrap().success());
1407 assert_eq!(out, "foobar\n");
1412 #[cfg_attr(target_os = "android", ignore)]
1415 use os::unix::prelude::*;
1417 let mut p = Command::new("/bin/sh")
1418 .arg("-c").arg("true")
1419 .uid(unsafe { libc::getuid() })
1420 .gid(unsafe { libc::getgid() })
1422 assert!(p.wait().unwrap().success());
1426 #[cfg_attr(target_os = "android", ignore)]
1428 fn uid_to_root_fails() {
1429 use os::unix::prelude::*;
1432 // if we're already root, this isn't a valid test. Most of the bots run
1433 // as non-root though (android is an exception).
1434 if unsafe { libc::getuid() == 0 } { return }
1435 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1439 #[cfg_attr(target_os = "android", ignore)]
1440 fn test_process_status() {
1441 let mut status = if cfg!(target_os = "windows") {
1442 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1444 Command::new("false").status().unwrap()
1446 assert!(status.code() == Some(1));
1448 status = if cfg!(target_os = "windows") {
1449 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1451 Command::new("true").status().unwrap()
1453 assert!(status.success());
1457 fn test_process_output_fail_to_start() {
1458 match Command::new("/no-binary-by-this-name-should-exist").output() {
1459 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1465 #[cfg_attr(target_os = "android", ignore)]
1466 fn test_process_output_output() {
1467 let Output {status, stdout, stderr}
1468 = if cfg!(target_os = "windows") {
1469 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1471 Command::new("echo").arg("hello").output().unwrap()
1473 let output_str = str::from_utf8(&stdout).unwrap();
1475 assert!(status.success());
1476 assert_eq!(output_str.trim().to_string(), "hello");
1477 assert_eq!(stderr, Vec::new());
1481 #[cfg_attr(target_os = "android", ignore)]
1482 fn test_process_output_error() {
1483 let Output {status, stdout, stderr}
1484 = if cfg!(target_os = "windows") {
1485 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1487 Command::new("mkdir").arg(".").output().unwrap()
1490 assert!(status.code() == Some(1));
1491 assert_eq!(stdout, Vec::new());
1492 assert!(!stderr.is_empty());
1496 #[cfg_attr(target_os = "android", ignore)]
1497 fn test_finish_once() {
1498 let mut prog = if cfg!(target_os = "windows") {
1499 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1501 Command::new("false").spawn().unwrap()
1503 assert!(prog.wait().unwrap().code() == Some(1));
1507 #[cfg_attr(target_os = "android", ignore)]
1508 fn test_finish_twice() {
1509 let mut prog = if cfg!(target_os = "windows") {
1510 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1512 Command::new("false").spawn().unwrap()
1514 assert!(prog.wait().unwrap().code() == Some(1));
1515 assert!(prog.wait().unwrap().code() == Some(1));
1519 #[cfg_attr(target_os = "android", ignore)]
1520 fn test_wait_with_output_once() {
1521 let prog = if cfg!(target_os = "windows") {
1522 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1524 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1527 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1528 let output_str = str::from_utf8(&stdout).unwrap();
1530 assert!(status.success());
1531 assert_eq!(output_str.trim().to_string(), "hello");
1532 assert_eq!(stderr, Vec::new());
1535 #[cfg(all(unix, not(target_os="android")))]
1536 pub fn env_cmd() -> Command {
1539 #[cfg(target_os="android")]
1540 pub fn env_cmd() -> Command {
1541 let mut cmd = Command::new("/system/bin/sh");
1542 cmd.arg("-c").arg("set");
1547 pub fn env_cmd() -> Command {
1548 let mut cmd = Command::new("cmd");
1549 cmd.arg("/c").arg("set");
1554 fn test_inherit_env() {
1557 let result = env_cmd().output().unwrap();
1558 let output = String::from_utf8(result.stdout).unwrap();
1560 for (ref k, ref v) in env::vars() {
1561 // Don't check android RANDOM variable which seems to change
1562 // whenever the shell runs, and our `env_cmd` is indeed running a
1563 // shell which means it'll get a different RANDOM than we probably
1566 // Also skip env vars with `-` in the name on android because, well,
1567 // I'm not sure. It appears though that the `set` command above does
1568 // not print env vars with `-` in the name, so we just skip them
1569 // here as we won't find them in the output. Note that most env vars
1570 // use `_` instead of `-`, but our build system sets a few env vars
1571 // with `-` in the name.
1572 if cfg!(target_os = "android") &&
1573 (*k == "RANDOM" || k.contains("-")) {
1577 // Windows has hidden environment variables whose names start with
1578 // equals signs (`=`). Those do not show up in the output of the
1580 assert!((cfg!(windows) && k.starts_with("=")) ||
1581 k.starts_with("DYLD") ||
1582 output.contains(&format!("{}={}", *k, *v)) ||
1583 output.contains(&format!("{}='{}'", *k, *v)),
1584 "output doesn't contain `{}={}`\n{}",
1590 fn test_override_env() {
1593 // In some build environments (such as chrooted Nix builds), `env` can
1594 // only be found in the explicitly-provided PATH env variable, not in
1595 // default places such as /bin or /usr/bin. So we need to pass through
1596 // PATH to our sub-process.
1597 let mut cmd = env_cmd();
1598 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1599 if let Some(p) = env::var_os("PATH") {
1600 cmd.env("PATH", &p);
1602 let result = cmd.output().unwrap();
1603 let output = String::from_utf8_lossy(&result.stdout).to_string();
1605 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1606 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1610 fn test_add_to_env() {
1611 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1612 let output = String::from_utf8_lossy(&result.stdout).to_string();
1614 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1615 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1618 // Regression tests for #30858.
1620 fn test_interior_nul_in_progname_is_error() {
1621 match Command::new("has-some-\0\0s-inside").spawn() {
1622 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1628 fn test_interior_nul_in_arg_is_error() {
1629 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1630 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1636 fn test_interior_nul_in_args_is_error() {
1637 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1638 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1644 fn test_interior_nul_in_current_dir_is_error() {
1645 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1646 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1651 // Regression tests for #30862.
1653 fn test_interior_nul_in_env_key_is_error() {
1654 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1655 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1661 fn test_interior_nul_in_env_value_is_error() {
1662 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1663 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1668 /// Test that process creation flags work by debugging a process.
1669 /// Other creation flags make it hard or impossible to detect
1670 /// behavioral changes in the process.
1673 fn test_creation_flags() {
1674 use os::windows::process::CommandExt;
1675 use sys::c::{BOOL, DWORD, INFINITE};
1677 struct DEBUG_EVENT {
1678 pub event_code: DWORD,
1679 pub process_id: DWORD,
1680 pub thread_id: DWORD,
1681 // This is a union in the real struct, but we don't
1682 // need this data for the purposes of this test.
1683 pub _junk: [u8; 164],
1687 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1688 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1689 dwContinueStatus: DWORD) -> BOOL;
1692 const DEBUG_PROCESS: DWORD = 1;
1693 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1694 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1696 let mut child = Command::new("cmd")
1697 .creation_flags(DEBUG_PROCESS)
1698 .stdin(Stdio::piped()).spawn().unwrap();
1699 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1701 let mut event = DEBUG_EVENT {
1708 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1709 panic!("WaitForDebugEvent failed!");
1713 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1717 if unsafe { ContinueDebugEvent(event.process_id,
1719 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1720 panic!("ContinueDebugEvent failed!");
1723 assert!(events > 0);