1 //! A module for working with processes.
3 //! This module is mostly concerned with spawning and interacting with child
4 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
7 //! # Spawning a process
9 //! The [`Command`] struct is used to configure and spawn processes:
12 //! use std::process::Command;
14 //! let output = Command::new("echo")
15 //! .arg("Hello world")
17 //! .expect("Failed to execute command");
19 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
22 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
23 //! to spawn a process. In particular, [`output`] spawns the child process and
24 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
25 //! that represents the spawned child process.
29 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
30 //! configured by passing an [`Stdio`] to the corresponding method on
31 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
32 //! example, piping output from one command into another command can be done
36 //! use std::process::{Command, Stdio};
38 //! // stdout must be configured with `Stdio::piped` in order to use
39 //! // `echo_child.stdout`
40 //! let echo_child = Command::new("echo")
41 //! .arg("Oh no, a tpyo!")
42 //! .stdout(Stdio::piped())
44 //! .expect("Failed to start echo process");
46 //! // Note that `echo_child` is moved here, but we won't be needing
47 //! // `echo_child` anymore
48 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
50 //! let mut sed_child = Command::new("sed")
51 //! .arg("s/tpyo/typo/")
52 //! .stdin(Stdio::from(echo_out))
53 //! .stdout(Stdio::piped())
55 //! .expect("Failed to start sed process");
57 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
58 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
61 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
62 //! [`ChildStdin`] implements [`Write`]:
65 //! use std::process::{Command, Stdio};
66 //! use std::io::Write;
68 //! let mut child = Command::new("/bin/cat")
69 //! .stdin(Stdio::piped())
70 //! .stdout(Stdio::piped())
72 //! .expect("failed to execute child");
75 //! // limited borrow of stdin
76 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
77 //! stdin.write_all(b"test").expect("failed to write to stdin");
80 //! let output = child
81 //! .wait_with_output()
82 //! .expect("failed to wait on child");
84 //! assert_eq!(b"test", output.stdout.as_slice());
87 //! [`abort`]: fn.abort.html
88 //! [`exit`]: fn.exit.html
90 //! [`Command`]: struct.Command.html
91 //! [`spawn`]: struct.Command.html#method.spawn
92 //! [`output`]: struct.Command.html#method.output
94 //! [`Child`]: struct.Child.html
95 //! [`ChildStdin`]: struct.ChildStdin.html
96 //! [`ChildStdout`]: struct.ChildStdout.html
97 //! [`ChildStderr`]: struct.ChildStderr.html
98 //! [`Stdio`]: struct.Stdio.html
100 //! [`stdout`]: struct.Command.html#method.stdout
101 //! [`stdin`]: struct.Command.html#method.stdin
102 //! [`stderr`]: struct.Command.html#method.stderr
104 //! [`Write`]: ../io/trait.Write.html
105 //! [`Read`]: ../io/trait.Read.html
107 #![stable(feature = "process", since = "1.0.0")]
114 use io::{self, Initializer};
117 use sys::pipe::{read2, AnonPipe};
118 use sys::process as imp;
119 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
121 /// Representation of a running or exited child process.
123 /// This structure is used to represent and manage child processes. A child
124 /// process is created via the [`Command`] struct, which configures the
125 /// spawning process and can itself be constructed using a builder-style
128 /// There is no implementation of [`Drop`] for child processes,
129 /// so if you do not ensure the `Child` has exited then it will continue to
130 /// run, even after the `Child` handle to the child process has gone out of
133 /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
134 /// the parent process wait until the child has actually exited before
140 /// use std::process::Command;
142 /// let mut child = Command::new("/bin/cat")
145 /// .expect("failed to execute child");
147 /// let ecode = child.wait()
148 /// .expect("failed to wait on child");
150 /// assert!(ecode.success());
153 /// [`Command`]: struct.Command.html
154 /// [`Drop`]: ../../core/ops/trait.Drop.html
155 /// [`wait`]: #method.wait
156 #[stable(feature = "process", since = "1.0.0")]
158 handle: imp::Process,
160 /// The handle for writing to the child's standard input (stdin), if it has
162 #[stable(feature = "process", since = "1.0.0")]
163 pub stdin: Option<ChildStdin>,
165 /// The handle for reading from the child's standard output (stdout), if it
166 /// has been captured.
167 #[stable(feature = "process", since = "1.0.0")]
168 pub stdout: Option<ChildStdout>,
170 /// The handle for reading from the child's standard error (stderr), if it
171 /// has been captured.
172 #[stable(feature = "process", since = "1.0.0")]
173 pub stderr: Option<ChildStderr>,
176 impl AsInner<imp::Process> for Child {
177 fn as_inner(&self) -> &imp::Process { &self.handle }
180 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
181 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
184 stdin: io.stdin.map(ChildStdin::from_inner),
185 stdout: io.stdout.map(ChildStdout::from_inner),
186 stderr: io.stderr.map(ChildStderr::from_inner),
191 impl IntoInner<imp::Process> for Child {
192 fn into_inner(self) -> imp::Process { self.handle }
195 #[stable(feature = "std_debug", since = "1.16.0")]
196 impl fmt::Debug for Child {
197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
198 f.debug_struct("Child")
199 .field("stdin", &self.stdin)
200 .field("stdout", &self.stdout)
201 .field("stderr", &self.stderr)
206 /// A handle to a child process's standard input (stdin).
208 /// This struct is used in the [`stdin`] field on [`Child`].
210 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
211 /// file handle will be closed. If the child process was blocked on input prior
212 /// to being dropped, it will become unblocked after dropping.
214 /// [`Child`]: struct.Child.html
215 /// [`stdin`]: struct.Child.html#structfield.stdin
216 /// [dropped]: ../ops/trait.Drop.html
217 #[stable(feature = "process", since = "1.0.0")]
218 pub struct ChildStdin {
222 #[stable(feature = "process", since = "1.0.0")]
223 impl Write for ChildStdin {
224 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
225 self.inner.write(buf)
228 fn flush(&mut self) -> io::Result<()> {
233 impl AsInner<AnonPipe> for ChildStdin {
234 fn as_inner(&self) -> &AnonPipe { &self.inner }
237 impl IntoInner<AnonPipe> for ChildStdin {
238 fn into_inner(self) -> AnonPipe { self.inner }
241 impl FromInner<AnonPipe> for ChildStdin {
242 fn from_inner(pipe: AnonPipe) -> ChildStdin {
243 ChildStdin { inner: pipe }
247 #[stable(feature = "std_debug", since = "1.16.0")]
248 impl fmt::Debug for ChildStdin {
249 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
250 f.pad("ChildStdin { .. }")
254 /// A handle to a child process's standard output (stdout).
256 /// This struct is used in the [`stdout`] field on [`Child`].
258 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
259 /// underlying file handle will be closed.
261 /// [`Child`]: struct.Child.html
262 /// [`stdout`]: struct.Child.html#structfield.stdout
263 /// [dropped]: ../ops/trait.Drop.html
264 #[stable(feature = "process", since = "1.0.0")]
265 pub struct ChildStdout {
269 #[stable(feature = "process", since = "1.0.0")]
270 impl Read for ChildStdout {
271 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
275 unsafe fn initializer(&self) -> Initializer {
280 impl AsInner<AnonPipe> for ChildStdout {
281 fn as_inner(&self) -> &AnonPipe { &self.inner }
284 impl IntoInner<AnonPipe> for ChildStdout {
285 fn into_inner(self) -> AnonPipe { self.inner }
288 impl FromInner<AnonPipe> for ChildStdout {
289 fn from_inner(pipe: AnonPipe) -> ChildStdout {
290 ChildStdout { inner: pipe }
294 #[stable(feature = "std_debug", since = "1.16.0")]
295 impl fmt::Debug for ChildStdout {
296 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
297 f.pad("ChildStdout { .. }")
301 /// A handle to a child process's stderr.
303 /// This struct is used in the [`stderr`] field on [`Child`].
305 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
306 /// underlying file handle will be closed.
308 /// [`Child`]: struct.Child.html
309 /// [`stderr`]: struct.Child.html#structfield.stderr
310 /// [dropped]: ../ops/trait.Drop.html
311 #[stable(feature = "process", since = "1.0.0")]
312 pub struct ChildStderr {
316 #[stable(feature = "process", since = "1.0.0")]
317 impl Read for ChildStderr {
318 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
322 unsafe fn initializer(&self) -> Initializer {
327 impl AsInner<AnonPipe> for ChildStderr {
328 fn as_inner(&self) -> &AnonPipe { &self.inner }
331 impl IntoInner<AnonPipe> for ChildStderr {
332 fn into_inner(self) -> AnonPipe { self.inner }
335 impl FromInner<AnonPipe> for ChildStderr {
336 fn from_inner(pipe: AnonPipe) -> ChildStderr {
337 ChildStderr { inner: pipe }
341 #[stable(feature = "std_debug", since = "1.16.0")]
342 impl fmt::Debug for ChildStderr {
343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
344 f.pad("ChildStderr { .. }")
348 /// A process builder, providing fine-grained control
349 /// over how a new process should be spawned.
351 /// A default configuration can be
352 /// generated using `Command::new(program)`, where `program` gives a path to the
353 /// program to be executed. Additional builder methods allow the configuration
354 /// to be changed (for example, by adding arguments) prior to spawning:
357 /// use std::process::Command;
359 /// let output = if cfg!(target_os = "windows") {
360 /// Command::new("cmd")
361 /// .args(&["/C", "echo hello"])
363 /// .expect("failed to execute process")
365 /// Command::new("sh")
367 /// .arg("echo hello")
369 /// .expect("failed to execute process")
372 /// let hello = output.stdout;
375 /// `Command` can be reused to spawn multiple processes. The builder methods
376 /// change the command without needing to immediately spawn the process.
379 /// use std::process::Command;
381 /// let mut echo_hello = Command::new("sh");
382 /// echo_hello.arg("-c")
383 /// .arg("echo hello");
384 /// let hello_1 = echo_hello.output().expect("failed to execute process");
385 /// let hello_2 = echo_hello.output().expect("failed to execute process");
388 /// Similarly, you can call builder methods after spawning a process and then
389 /// spawn a new process with the modified settings.
392 /// use std::process::Command;
394 /// let mut list_dir = Command::new("ls");
396 /// // Execute `ls` in the current directory of the program.
397 /// list_dir.status().expect("process failed to execute");
401 /// // Change `ls` to execute in the root directory.
402 /// list_dir.current_dir("/");
404 /// // And then execute `ls` again but in the root directory.
405 /// list_dir.status().expect("process failed to execute");
407 #[stable(feature = "process", since = "1.0.0")]
413 /// Constructs a new `Command` for launching the program at
414 /// path `program`, with the following default configuration:
416 /// * No arguments to the program
417 /// * Inherit the current process's environment
418 /// * Inherit the current process's working directory
419 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
421 /// Builder methods are provided to change these defaults and
422 /// otherwise configure the process.
424 /// If `program` is not an absolute path, the `PATH` will be searched in
425 /// an OS-defined way.
427 /// The search path to be used may be controlled by setting the
428 /// `PATH` environment variable on the Command,
429 /// but this has some implementation limitations on Windows
430 /// (see <https://github.com/rust-lang/rust/issues/37519>).
437 /// use std::process::Command;
439 /// Command::new("sh")
441 /// .expect("sh command failed to start");
443 #[stable(feature = "process", since = "1.0.0")]
444 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
445 Command { inner: imp::Command::new(program.as_ref()) }
448 /// Add an argument to pass to the program.
450 /// Only one argument can be passed per use. So instead of:
453 /// # std::process::Command::new("sh")
454 /// .arg("-C /path/to/repo")
461 /// # std::process::Command::new("sh")
463 /// .arg("/path/to/repo")
467 /// To pass multiple arguments see [`args`].
469 /// [`args`]: #method.args
476 /// use std::process::Command;
478 /// Command::new("ls")
482 /// .expect("ls command failed to start");
484 #[stable(feature = "process", since = "1.0.0")]
485 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
486 self.inner.arg(arg.as_ref());
490 /// Add multiple arguments to pass to the program.
492 /// To pass a single argument see [`arg`].
494 /// [`arg`]: #method.arg
501 /// use std::process::Command;
503 /// Command::new("ls")
504 /// .args(&["-l", "-a"])
506 /// .expect("ls command failed to start");
508 #[stable(feature = "process", since = "1.0.0")]
509 pub fn args<I, S>(&mut self, args: I) -> &mut Command
510 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
513 self.arg(arg.as_ref());
518 /// Inserts or updates an environment variable mapping.
520 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
521 /// and case-sensitive on all other platforms.
528 /// use std::process::Command;
530 /// Command::new("ls")
531 /// .env("PATH", "/bin")
533 /// .expect("ls command failed to start");
535 #[stable(feature = "process", since = "1.0.0")]
536 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
537 where K: AsRef<OsStr>, V: AsRef<OsStr>
539 self.inner.env_mut().set(key.as_ref(), val.as_ref());
543 /// Add or update multiple environment variable mappings.
550 /// use std::process::{Command, Stdio};
552 /// use std::collections::HashMap;
554 /// let filtered_env : HashMap<String, String> =
555 /// env::vars().filter(|&(ref k, _)|
556 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
559 /// Command::new("printenv")
560 /// .stdin(Stdio::null())
561 /// .stdout(Stdio::inherit())
563 /// .envs(&filtered_env)
565 /// .expect("printenv failed to start");
567 #[stable(feature = "command_envs", since = "1.19.0")]
568 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
569 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
571 for (ref key, ref val) in vars {
572 self.inner.env_mut().set(key.as_ref(), val.as_ref());
577 /// Removes an environment variable mapping.
584 /// use std::process::Command;
586 /// Command::new("ls")
587 /// .env_remove("PATH")
589 /// .expect("ls command failed to start");
591 #[stable(feature = "process", since = "1.0.0")]
592 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
593 self.inner.env_mut().remove(key.as_ref());
597 /// Clears the entire environment map for the child process.
604 /// use std::process::Command;
606 /// Command::new("ls")
609 /// .expect("ls command failed to start");
611 #[stable(feature = "process", since = "1.0.0")]
612 pub fn env_clear(&mut self) -> &mut Command {
613 self.inner.env_mut().clear();
617 /// Sets the working directory for the child process.
619 /// # Platform-specific behavior
621 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
622 /// whether it should be interpreted relative to the parent's working
623 /// directory or relative to `current_dir`. The behavior in this case is
624 /// platform specific and unstable, and it's recommended to use
625 /// [`canonicalize`] to get an absolute program path instead.
632 /// use std::process::Command;
634 /// Command::new("ls")
635 /// .current_dir("/bin")
637 /// .expect("ls command failed to start");
640 /// [`canonicalize`]: ../fs/fn.canonicalize.html
641 #[stable(feature = "process", since = "1.0.0")]
642 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
643 self.inner.cwd(dir.as_ref().as_ref());
647 /// Configuration for the child process's standard input (stdin) handle.
649 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
650 /// defaults to [`piped`] when used with `output`.
652 /// [`inherit`]: struct.Stdio.html#method.inherit
653 /// [`piped`]: struct.Stdio.html#method.piped
660 /// use std::process::{Command, Stdio};
662 /// Command::new("ls")
663 /// .stdin(Stdio::null())
665 /// .expect("ls command failed to start");
667 #[stable(feature = "process", since = "1.0.0")]
668 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
669 self.inner.stdin(cfg.into().0);
673 /// Configuration for the child process's standard output (stdout) handle.
675 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
676 /// defaults to [`piped`] when used with `output`.
678 /// [`inherit`]: struct.Stdio.html#method.inherit
679 /// [`piped`]: struct.Stdio.html#method.piped
686 /// use std::process::{Command, Stdio};
688 /// Command::new("ls")
689 /// .stdout(Stdio::null())
691 /// .expect("ls command failed to start");
693 #[stable(feature = "process", since = "1.0.0")]
694 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
695 self.inner.stdout(cfg.into().0);
699 /// Configuration for the child process's standard error (stderr) handle.
701 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
702 /// defaults to [`piped`] when used with `output`.
704 /// [`inherit`]: struct.Stdio.html#method.inherit
705 /// [`piped`]: struct.Stdio.html#method.piped
712 /// use std::process::{Command, Stdio};
714 /// Command::new("ls")
715 /// .stderr(Stdio::null())
717 /// .expect("ls command failed to start");
719 #[stable(feature = "process", since = "1.0.0")]
720 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
721 self.inner.stderr(cfg.into().0);
725 /// Executes the command as a child process, returning a handle to it.
727 /// By default, stdin, stdout and stderr are inherited from the parent.
734 /// use std::process::Command;
736 /// Command::new("ls")
738 /// .expect("ls command failed to start");
740 #[stable(feature = "process", since = "1.0.0")]
741 pub fn spawn(&mut self) -> io::Result<Child> {
742 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
745 /// Executes the command as a child process, waiting for it to finish and
746 /// collecting all of its output.
748 /// By default, stdout and stderr are captured (and used to provide the
749 /// resulting output). Stdin is not inherited from the parent and any
750 /// attempt by the child process to read from the stdin stream will result
751 /// in the stream immediately closing.
756 /// use std::process::Command;
757 /// use std::io::{self, Write};
758 /// let output = Command::new("/bin/cat")
761 /// .expect("failed to execute process");
763 /// println!("status: {}", output.status);
764 /// io::stdout().write_all(&output.stdout).unwrap();
765 /// io::stderr().write_all(&output.stderr).unwrap();
767 /// assert!(output.status.success());
769 #[stable(feature = "process", since = "1.0.0")]
770 pub fn output(&mut self) -> io::Result<Output> {
771 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
772 .and_then(|p| p.wait_with_output())
775 /// Executes a command as a child process, waiting for it to finish and
776 /// collecting its exit status.
778 /// By default, stdin, stdout and stderr are inherited from the parent.
783 /// use std::process::Command;
785 /// let status = Command::new("/bin/cat")
788 /// .expect("failed to execute process");
790 /// println!("process exited with: {}", status);
792 /// assert!(status.success());
794 #[stable(feature = "process", since = "1.0.0")]
795 pub fn status(&mut self) -> io::Result<ExitStatus> {
796 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
797 .and_then(|mut p| p.wait())
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl fmt::Debug for Command {
803 /// Format the program and arguments of a Command for display. Any
804 /// non-utf8 data is lossily converted using the utf8 replacement
806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
811 impl AsInner<imp::Command> for Command {
812 fn as_inner(&self) -> &imp::Command { &self.inner }
815 impl AsInnerMut<imp::Command> for Command {
816 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
819 /// The output of a finished process.
821 /// This is returned in a Result by either the [`output`] method of a
822 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
825 /// [`Command`]: struct.Command.html
826 /// [`Child`]: struct.Child.html
827 /// [`output`]: struct.Command.html#method.output
828 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
829 #[derive(PartialEq, Eq, Clone)]
830 #[stable(feature = "process", since = "1.0.0")]
832 /// The status (exit code) of the process.
833 #[stable(feature = "process", since = "1.0.0")]
834 pub status: ExitStatus,
835 /// The data that the process wrote to stdout.
836 #[stable(feature = "process", since = "1.0.0")]
838 /// The data that the process wrote to stderr.
839 #[stable(feature = "process", since = "1.0.0")]
843 // If either stderr or stdout are valid utf8 strings it prints the valid
844 // strings, otherwise it prints the byte sequence instead
845 #[stable(feature = "process_output_debug", since = "1.7.0")]
846 impl fmt::Debug for Output {
847 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
849 let stdout_utf8 = str::from_utf8(&self.stdout);
850 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
852 Err(_) => &self.stdout
855 let stderr_utf8 = str::from_utf8(&self.stderr);
856 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
858 Err(_) => &self.stderr
861 fmt.debug_struct("Output")
862 .field("status", &self.status)
863 .field("stdout", stdout_debug)
864 .field("stderr", stderr_debug)
869 /// Describes what to do with a standard I/O stream for a child process when
870 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
872 /// [`stdin`]: struct.Command.html#method.stdin
873 /// [`stdout`]: struct.Command.html#method.stdout
874 /// [`stderr`]: struct.Command.html#method.stderr
875 /// [`Command`]: struct.Command.html
876 #[stable(feature = "process", since = "1.0.0")]
877 pub struct Stdio(imp::Stdio);
880 /// A new pipe should be arranged to connect the parent and child processes.
887 /// use std::process::{Command, Stdio};
889 /// let output = Command::new("echo")
890 /// .arg("Hello, world!")
891 /// .stdout(Stdio::piped())
893 /// .expect("Failed to execute command");
895 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
896 /// // Nothing echoed to console
902 /// use std::io::Write;
903 /// use std::process::{Command, Stdio};
905 /// let mut child = Command::new("rev")
906 /// .stdin(Stdio::piped())
907 /// .stdout(Stdio::piped())
909 /// .expect("Failed to spawn child process");
912 /// let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
913 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
916 /// let output = child.wait_with_output().expect("Failed to read stdout");
917 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
919 #[stable(feature = "process", since = "1.0.0")]
920 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
922 /// The child inherits from the corresponding parent descriptor.
929 /// use std::process::{Command, Stdio};
931 /// let output = Command::new("echo")
932 /// .arg("Hello, world!")
933 /// .stdout(Stdio::inherit())
935 /// .expect("Failed to execute command");
937 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
938 /// // "Hello, world!" echoed to console
944 /// use std::process::{Command, Stdio};
945 /// use std::io::{self, Write};
947 /// let output = Command::new("rev")
948 /// .stdin(Stdio::inherit())
949 /// .stdout(Stdio::piped())
951 /// .expect("Failed to execute command");
953 /// print!("You piped in the reverse of: ");
954 /// io::stdout().write_all(&output.stdout).unwrap();
956 #[stable(feature = "process", since = "1.0.0")]
957 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
959 /// This stream will be ignored. This is the equivalent of attaching the
960 /// stream to `/dev/null`
967 /// use std::process::{Command, Stdio};
969 /// let output = Command::new("echo")
970 /// .arg("Hello, world!")
971 /// .stdout(Stdio::null())
973 /// .expect("Failed to execute command");
975 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
976 /// // Nothing echoed to console
982 /// use std::process::{Command, Stdio};
984 /// let output = Command::new("rev")
985 /// .stdin(Stdio::null())
986 /// .stdout(Stdio::piped())
988 /// .expect("Failed to execute command");
990 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
991 /// // Ignores any piped-in input
993 #[stable(feature = "process", since = "1.0.0")]
994 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
997 impl FromInner<imp::Stdio> for Stdio {
998 fn from_inner(inner: imp::Stdio) -> Stdio {
1003 #[stable(feature = "std_debug", since = "1.16.0")]
1004 impl fmt::Debug for Stdio {
1005 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1006 f.pad("Stdio { .. }")
1010 #[stable(feature = "stdio_from", since = "1.20.0")]
1011 impl From<ChildStdin> for Stdio {
1012 /// Converts a `ChildStdin` into a `Stdio`
1016 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1019 /// use std::process::{Command, Stdio};
1021 /// let reverse = Command::new("rev")
1022 /// .stdin(Stdio::piped())
1024 /// .expect("failed reverse command");
1026 /// let _echo = Command::new("echo")
1027 /// .arg("Hello, world!")
1028 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1030 /// .expect("failed echo command");
1032 /// // "!dlrow ,olleH" echoed to console
1034 fn from(child: ChildStdin) -> Stdio {
1035 Stdio::from_inner(child.into_inner().into())
1039 #[stable(feature = "stdio_from", since = "1.20.0")]
1040 impl From<ChildStdout> for Stdio {
1041 /// Converts a `ChildStdout` into a `Stdio`
1045 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1048 /// use std::process::{Command, Stdio};
1050 /// let hello = Command::new("echo")
1051 /// .arg("Hello, world!")
1052 /// .stdout(Stdio::piped())
1054 /// .expect("failed echo command");
1056 /// let reverse = Command::new("rev")
1057 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1059 /// .expect("failed reverse command");
1061 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1063 fn from(child: ChildStdout) -> Stdio {
1064 Stdio::from_inner(child.into_inner().into())
1068 #[stable(feature = "stdio_from", since = "1.20.0")]
1069 impl From<ChildStderr> for Stdio {
1070 /// Converts a `ChildStderr` into a `Stdio`
1075 /// use std::process::{Command, Stdio};
1077 /// let reverse = Command::new("rev")
1078 /// .arg("non_existing_file.txt")
1079 /// .stderr(Stdio::piped())
1081 /// .expect("failed reverse command");
1083 /// let cat = Command::new("cat")
1085 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1087 /// .expect("failed echo command");
1090 /// String::from_utf8_lossy(&cat.stdout),
1091 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1094 fn from(child: ChildStderr) -> Stdio {
1095 Stdio::from_inner(child.into_inner().into())
1099 #[stable(feature = "stdio_from", since = "1.20.0")]
1100 impl From<fs::File> for Stdio {
1101 /// Converts a `File` into a `Stdio`
1105 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1108 /// use std::fs::File;
1109 /// use std::process::Command;
1111 /// // With the `foo.txt` file containing `Hello, world!"
1112 /// let file = File::open("foo.txt").unwrap();
1114 /// let reverse = Command::new("rev")
1115 /// .stdin(file) // Implicit File conversion into a Stdio
1117 /// .expect("failed reverse command");
1119 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1121 fn from(file: fs::File) -> Stdio {
1122 Stdio::from_inner(file.into_inner().into())
1126 /// Describes the result of a process after it has terminated.
1128 /// This `struct` is used to represent the exit status of a child process.
1129 /// Child processes are created via the [`Command`] struct and their exit
1130 /// status is exposed through the [`status`] method.
1132 /// [`Command`]: struct.Command.html
1133 /// [`status`]: struct.Command.html#method.status
1134 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1135 #[stable(feature = "process", since = "1.0.0")]
1136 pub struct ExitStatus(imp::ExitStatus);
1139 /// Was termination successful? Signal termination is not considered a
1140 /// success, and success is defined as a zero exit status.
1145 /// use std::process::Command;
1147 /// let status = Command::new("mkdir")
1148 /// .arg("projects")
1150 /// .expect("failed to execute mkdir");
1152 /// if status.success() {
1153 /// println!("'projects/' directory created");
1155 /// println!("failed to create 'projects/' directory");
1158 #[stable(feature = "process", since = "1.0.0")]
1159 pub fn success(&self) -> bool {
1163 /// Returns the exit code of the process, if any.
1165 /// On Unix, this will return `None` if the process was terminated
1166 /// by a signal; `std::os::unix` provides an extension trait for
1167 /// extracting the signal and other details from the `ExitStatus`.
1172 /// use std::process::Command;
1174 /// let status = Command::new("mkdir")
1175 /// .arg("projects")
1177 /// .expect("failed to execute mkdir");
1179 /// match status.code() {
1180 /// Some(code) => println!("Exited with status code: {}", code),
1181 /// None => println!("Process terminated by signal")
1184 #[stable(feature = "process", since = "1.0.0")]
1185 pub fn code(&self) -> Option<i32> {
1190 impl AsInner<imp::ExitStatus> for ExitStatus {
1191 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
1194 impl FromInner<imp::ExitStatus> for ExitStatus {
1195 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1200 #[stable(feature = "process", since = "1.0.0")]
1201 impl fmt::Display for ExitStatus {
1202 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1207 /// This type represents the status code a process can return to its
1208 /// parent under normal termination.
1210 /// Numeric values used in this type don't have portable meanings, and
1211 /// different platforms may mask different amounts of them.
1213 /// For the platform's canonical successful and unsuccessful codes, see
1214 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1216 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1217 /// [`FAILURE`]: #associatedconstant.FAILURE
1219 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1220 /// it was ultimately cut from that RFC, and thus this type is more subject
1221 /// to change even than the usual unstable item churn.
1223 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1224 #[derive(Clone, Copy, Debug)]
1225 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1226 pub struct ExitCode(imp::ExitCode);
1228 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1230 /// The canonical ExitCode for successful termination on this platform.
1232 /// Note that a `()`-returning `main` implicitly results in a successful
1233 /// termination, so there's no need to return this from `main` unless
1234 /// you're also returning other possible codes.
1235 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1236 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1238 /// The canonical ExitCode for unsuccessful termination on this platform.
1240 /// If you're only returning this and `SUCCESS` from `main`, consider
1241 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1242 /// return the same codes (but will also `eprintln!` the error).
1243 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1244 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1248 /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1249 /// error is returned.
1251 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1252 /// especially the [`Other`] kind might change to more specific kinds in the future.
1254 /// This is equivalent to sending a SIGKILL on Unix platforms.
1261 /// use std::process::Command;
1263 /// let mut command = Command::new("yes");
1264 /// if let Ok(mut child) = command.spawn() {
1265 /// child.kill().expect("command wasn't running");
1267 /// println!("yes command didn't start");
1271 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1272 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1273 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1274 #[stable(feature = "process", since = "1.0.0")]
1275 pub fn kill(&mut self) -> io::Result<()> {
1279 /// Returns the OS-assigned process identifier associated with this child.
1286 /// use std::process::Command;
1288 /// let mut command = Command::new("ls");
1289 /// if let Ok(child) = command.spawn() {
1290 /// println!("Child's id is {}", child.id());
1292 /// println!("ls command didn't start");
1295 #[stable(feature = "process_id", since = "1.3.0")]
1296 pub fn id(&self) -> u32 {
1300 /// Waits for the child to exit completely, returning the status that it
1301 /// exited with. This function will continue to have the same return value
1302 /// after it has been called at least once.
1304 /// The stdin handle to the child process, if any, will be closed
1305 /// before waiting. This helps avoid deadlock: it ensures that the
1306 /// child does not block waiting for input from the parent, while
1307 /// the parent waits for the child to exit.
1314 /// use std::process::Command;
1316 /// let mut command = Command::new("ls");
1317 /// if let Ok(mut child) = command.spawn() {
1318 /// child.wait().expect("command wasn't running");
1319 /// println!("Child has finished its execution!");
1321 /// println!("ls command didn't start");
1324 #[stable(feature = "process", since = "1.0.0")]
1325 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1326 drop(self.stdin.take());
1327 self.handle.wait().map(ExitStatus)
1330 /// Attempts to collect the exit status of the child if it has already
1333 /// This function will not block the calling thread and will only
1334 /// check to see if the child process has exited or not. If the child has
1335 /// exited then on Unix the process id is reaped. This function is
1336 /// guaranteed to repeatedly return a successful exit status so long as the
1337 /// child has already exited.
1339 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1340 /// exit status is not available at this time then `Ok(None)` is returned.
1341 /// If an error occurs, then that error is returned.
1343 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1350 /// use std::process::Command;
1352 /// let mut child = Command::new("ls").spawn().unwrap();
1354 /// match child.try_wait() {
1355 /// Ok(Some(status)) => println!("exited with: {}", status),
1357 /// println!("status not ready yet, let's really wait");
1358 /// let res = child.wait();
1359 /// println!("result: {:?}", res);
1361 /// Err(e) => println!("error attempting to wait: {}", e),
1364 #[stable(feature = "process_try_wait", since = "1.18.0")]
1365 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1366 Ok(self.handle.try_wait()?.map(ExitStatus))
1369 /// Simultaneously waits for the child to exit and collect all remaining
1370 /// output on the stdout/stderr handles, returning an `Output`
1373 /// The stdin handle to the child process, if any, will be closed
1374 /// before waiting. This helps avoid deadlock: it ensures that the
1375 /// child does not block waiting for input from the parent, while
1376 /// the parent waits for the child to exit.
1378 /// By default, stdin, stdout and stderr are inherited from the parent.
1379 /// In order to capture the output into this `Result<Output>` it is
1380 /// necessary to create new pipes between parent and child. Use
1381 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1386 /// use std::process::{Command, Stdio};
1388 /// let child = Command::new("/bin/cat")
1389 /// .arg("file.txt")
1390 /// .stdout(Stdio::piped())
1392 /// .expect("failed to execute child");
1394 /// let output = child
1395 /// .wait_with_output()
1396 /// .expect("failed to wait on child");
1398 /// assert!(output.status.success());
1401 #[stable(feature = "process", since = "1.0.0")]
1402 pub fn wait_with_output(mut self) -> io::Result<Output> {
1403 drop(self.stdin.take());
1405 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1406 match (self.stdout.take(), self.stderr.take()) {
1408 (Some(mut out), None) => {
1409 let res = out.read_to_end(&mut stdout);
1412 (None, Some(mut err)) => {
1413 let res = err.read_to_end(&mut stderr);
1416 (Some(out), Some(err)) => {
1417 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1422 let status = self.wait()?;
1431 /// Terminates the current process with the specified exit code.
1433 /// This function will never return and will immediately terminate the current
1434 /// process. The exit code is passed through to the underlying OS and will be
1435 /// available for consumption by another process.
1437 /// Note that because this function never returns, and that it terminates the
1438 /// process, no destructors on the current stack or any other thread's stack
1439 /// will be run. If a clean shutdown is needed it is recommended to only call
1440 /// this function at a known point where there are no more destructors left
1443 /// ## Platform-specific behavior
1445 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1446 /// will be visible to a parent process inspecting the exit code. On most
1447 /// Unix-like platforms, only the eight least-significant bits are considered.
1451 /// Due to this function’s behavior regarding destructors, a conventional way
1452 /// to use the function is to extract the actual computation to another
1453 /// function and compute the exit code from its return value:
1456 /// fn run_app() -> Result<(), ()> {
1457 /// // Application logic here
1462 /// ::std::process::exit(match run_app() {
1465 /// eprintln!("error: {:?}", err);
1472 /// Due to [platform-specific behavior], the exit code for this example will be
1473 /// `0` on Linux, but `256` on Windows:
1476 /// use std::process;
1478 /// process::exit(0x0100);
1481 /// [platform-specific behavior]: #platform-specific-behavior
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 pub fn exit(code: i32) -> ! {
1484 ::sys_common::cleanup();
1485 ::sys::os::exit(code)
1488 /// Terminates the process in an abnormal fashion.
1490 /// The function will never return and will immediately terminate the current
1491 /// process in a platform specific "abnormal" manner.
1493 /// Note that because this function never returns, and that it terminates the
1494 /// process, no destructors on the current stack or any other thread's stack
1497 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1498 /// the current thread's stack and calls all destructors.
1499 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1500 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1501 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1503 /// If a clean shutdown is needed it is recommended to only call
1504 /// this function at a known point where there are no more destructors left
1510 /// use std::process;
1513 /// println!("aborting");
1515 /// process::abort();
1517 /// // execution never gets here
1521 /// The `abort` function terminates the process, so the destructor will not
1522 /// get run on the example below:
1525 /// use std::process;
1529 /// impl Drop for HasDrop {
1530 /// fn drop(&mut self) {
1531 /// println!("This will never be printed!");
1536 /// let _x = HasDrop;
1537 /// process::abort();
1538 /// // the destructor implemented for HasDrop will never get run
1542 /// [`panic!`]: ../../std/macro.panic.html
1543 /// [panic hook]: ../../std/panic/fn.set_hook.html
1544 #[stable(feature = "process_abort", since = "1.17.0")]
1545 pub fn abort() -> ! {
1546 unsafe { ::sys::abort_internal() };
1549 /// Returns the OS-assigned process identifier associated with this process.
1556 /// use std::process;
1558 /// println!("My pid is {}", process::id());
1562 #[stable(feature = "getpid", since = "1.26.0")]
1563 pub fn id() -> u32 {
1567 /// A trait for implementing arbitrary return types in the `main` function.
1569 /// The c-main function only supports to return integers as return type.
1570 /// So, every type implementing the `Termination` trait has to be converted
1573 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1574 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1575 #[cfg_attr(not(test), lang = "termination")]
1576 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1577 #[rustc_on_unimplemented(
1578 message="`main` has invalid return type `{Self}`",
1579 label="`main` can only return types that implement `{Termination}`")]
1580 pub trait Termination {
1581 /// Is called to get the representation of the value as status code.
1582 /// This status code is returned to the operating system.
1583 fn report(self) -> i32;
1586 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1587 impl Termination for () {
1589 fn report(self) -> i32 { ExitCode::SUCCESS.report() }
1592 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1593 impl<E: fmt::Debug> Termination for Result<(), E> {
1594 fn report(self) -> i32 {
1596 Ok(()) => ().report(),
1597 Err(err) => Err::<!, _>(err).report(),
1602 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1603 impl Termination for ! {
1604 fn report(self) -> i32 { self }
1607 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1608 impl<E: fmt::Debug> Termination for Result<!, E> {
1609 fn report(self) -> i32 {
1610 let Err(err) = self;
1611 eprintln!("Error: {:?}", err);
1612 ExitCode::FAILURE.report()
1616 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1617 impl Termination for ExitCode {
1619 fn report(self) -> i32 {
1624 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
1630 use super::{Command, Output, Stdio};
1632 // FIXME(#10380) these tests should not all be ignored on android.
1635 #[cfg_attr(target_os = "android", ignore)]
1637 let p = if cfg!(target_os = "windows") {
1638 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1640 Command::new("true").spawn()
1643 let mut p = p.unwrap();
1644 assert!(p.wait().unwrap().success());
1648 #[cfg_attr(target_os = "android", ignore)]
1649 fn smoke_failure() {
1650 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1657 #[cfg_attr(target_os = "android", ignore)]
1658 fn exit_reported_right() {
1659 let p = if cfg!(target_os = "windows") {
1660 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1662 Command::new("false").spawn()
1665 let mut p = p.unwrap();
1666 assert!(p.wait().unwrap().code() == Some(1));
1672 #[cfg_attr(target_os = "android", ignore)]
1673 fn signal_reported_right() {
1674 use os::unix::process::ExitStatusExt;
1676 let mut p = Command::new("/bin/sh")
1677 .arg("-c").arg("read a")
1678 .stdin(Stdio::piped())
1681 match p.wait().unwrap().signal() {
1683 result => panic!("not terminated by signal 9 (instead, {:?})",
1688 pub fn run_output(mut cmd: Command) -> String {
1689 let p = cmd.spawn();
1691 let mut p = p.unwrap();
1692 assert!(p.stdout.is_some());
1693 let mut ret = String::new();
1694 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1695 assert!(p.wait().unwrap().success());
1700 #[cfg_attr(target_os = "android", ignore)]
1702 if cfg!(target_os = "windows") {
1703 let mut cmd = Command::new("cmd");
1704 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1705 assert_eq!(run_output(cmd), "foobar\r\n");
1707 let mut cmd = Command::new("echo");
1708 cmd.arg("foobar").stdout(Stdio::piped());
1709 assert_eq!(run_output(cmd), "foobar\n");
1714 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1715 fn set_current_dir_works() {
1716 let mut cmd = Command::new("/bin/sh");
1717 cmd.arg("-c").arg("pwd")
1719 .stdout(Stdio::piped());
1720 assert_eq!(run_output(cmd), "/\n");
1724 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1726 let mut p = Command::new("/bin/sh")
1727 .arg("-c").arg("read line; echo $line")
1728 .stdin(Stdio::piped())
1729 .stdout(Stdio::piped())
1731 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1732 drop(p.stdin.take());
1733 let mut out = String::new();
1734 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1735 assert!(p.wait().unwrap().success());
1736 assert_eq!(out, "foobar\n");
1741 #[cfg_attr(target_os = "android", ignore)]
1744 use os::unix::prelude::*;
1746 let mut p = Command::new("/bin/sh")
1747 .arg("-c").arg("true")
1748 .uid(unsafe { libc::getuid() })
1749 .gid(unsafe { libc::getgid() })
1751 assert!(p.wait().unwrap().success());
1755 #[cfg_attr(target_os = "android", ignore)]
1757 fn uid_to_root_fails() {
1758 use os::unix::prelude::*;
1761 // if we're already root, this isn't a valid test. Most of the bots run
1762 // as non-root though (android is an exception).
1763 if unsafe { libc::getuid() == 0 } { return }
1764 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1768 #[cfg_attr(target_os = "android", ignore)]
1769 fn test_process_status() {
1770 let mut status = if cfg!(target_os = "windows") {
1771 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1773 Command::new("false").status().unwrap()
1775 assert!(status.code() == Some(1));
1777 status = if cfg!(target_os = "windows") {
1778 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1780 Command::new("true").status().unwrap()
1782 assert!(status.success());
1786 fn test_process_output_fail_to_start() {
1787 match Command::new("/no-binary-by-this-name-should-exist").output() {
1788 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1794 #[cfg_attr(target_os = "android", ignore)]
1795 fn test_process_output_output() {
1796 let Output {status, stdout, stderr}
1797 = if cfg!(target_os = "windows") {
1798 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1800 Command::new("echo").arg("hello").output().unwrap()
1802 let output_str = str::from_utf8(&stdout).unwrap();
1804 assert!(status.success());
1805 assert_eq!(output_str.trim().to_string(), "hello");
1806 assert_eq!(stderr, Vec::new());
1810 #[cfg_attr(target_os = "android", ignore)]
1811 fn test_process_output_error() {
1812 let Output {status, stdout, stderr}
1813 = if cfg!(target_os = "windows") {
1814 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1816 Command::new("mkdir").arg("./").output().unwrap()
1819 assert!(status.code() == Some(1));
1820 assert_eq!(stdout, Vec::new());
1821 assert!(!stderr.is_empty());
1825 #[cfg_attr(target_os = "android", ignore)]
1826 fn test_finish_once() {
1827 let mut prog = if cfg!(target_os = "windows") {
1828 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1830 Command::new("false").spawn().unwrap()
1832 assert!(prog.wait().unwrap().code() == Some(1));
1836 #[cfg_attr(target_os = "android", ignore)]
1837 fn test_finish_twice() {
1838 let mut prog = if cfg!(target_os = "windows") {
1839 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1841 Command::new("false").spawn().unwrap()
1843 assert!(prog.wait().unwrap().code() == Some(1));
1844 assert!(prog.wait().unwrap().code() == Some(1));
1848 #[cfg_attr(target_os = "android", ignore)]
1849 fn test_wait_with_output_once() {
1850 let prog = if cfg!(target_os = "windows") {
1851 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1853 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1856 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1857 let output_str = str::from_utf8(&stdout).unwrap();
1859 assert!(status.success());
1860 assert_eq!(output_str.trim().to_string(), "hello");
1861 assert_eq!(stderr, Vec::new());
1864 #[cfg(all(unix, not(target_os="android")))]
1865 pub fn env_cmd() -> Command {
1868 #[cfg(target_os="android")]
1869 pub fn env_cmd() -> Command {
1870 let mut cmd = Command::new("/system/bin/sh");
1871 cmd.arg("-c").arg("set");
1876 pub fn env_cmd() -> Command {
1877 let mut cmd = Command::new("cmd");
1878 cmd.arg("/c").arg("set");
1883 fn test_override_env() {
1886 // In some build environments (such as chrooted Nix builds), `env` can
1887 // only be found in the explicitly-provided PATH env variable, not in
1888 // default places such as /bin or /usr/bin. So we need to pass through
1889 // PATH to our sub-process.
1890 let mut cmd = env_cmd();
1891 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1892 if let Some(p) = env::var_os("PATH") {
1893 cmd.env("PATH", &p);
1895 let result = cmd.output().unwrap();
1896 let output = String::from_utf8_lossy(&result.stdout).to_string();
1898 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1899 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1903 fn test_add_to_env() {
1904 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1905 let output = String::from_utf8_lossy(&result.stdout).to_string();
1907 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1908 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1912 fn test_capture_env_at_spawn() {
1915 let mut cmd = env_cmd();
1916 cmd.env("RUN_TEST_NEW_ENV1", "123");
1918 // This variable will not be present if the environment has already
1919 // been captured above.
1920 env::set_var("RUN_TEST_NEW_ENV2", "456");
1921 let result = cmd.output().unwrap();
1922 env::remove_var("RUN_TEST_NEW_ENV2");
1924 let output = String::from_utf8_lossy(&result.stdout).to_string();
1926 assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1927 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1928 assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1929 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1932 // Regression tests for #30858.
1934 fn test_interior_nul_in_progname_is_error() {
1935 match Command::new("has-some-\0\0s-inside").spawn() {
1936 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1942 fn test_interior_nul_in_arg_is_error() {
1943 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1944 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1950 fn test_interior_nul_in_args_is_error() {
1951 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1952 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1958 fn test_interior_nul_in_current_dir_is_error() {
1959 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1960 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1965 // Regression tests for #30862.
1967 fn test_interior_nul_in_env_key_is_error() {
1968 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1969 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1975 fn test_interior_nul_in_env_value_is_error() {
1976 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1977 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1982 /// Test that process creation flags work by debugging a process.
1983 /// Other creation flags make it hard or impossible to detect
1984 /// behavioral changes in the process.
1987 fn test_creation_flags() {
1988 use os::windows::process::CommandExt;
1989 use sys::c::{BOOL, DWORD, INFINITE};
1991 struct DEBUG_EVENT {
1992 pub event_code: DWORD,
1993 pub process_id: DWORD,
1994 pub thread_id: DWORD,
1995 // This is a union in the real struct, but we don't
1996 // need this data for the purposes of this test.
1997 pub _junk: [u8; 164],
2001 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
2002 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
2003 dwContinueStatus: DWORD) -> BOOL;
2006 const DEBUG_PROCESS: DWORD = 1;
2007 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
2008 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
2010 let mut child = Command::new("cmd")
2011 .creation_flags(DEBUG_PROCESS)
2012 .stdin(Stdio::piped()).spawn().unwrap();
2013 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
2015 let mut event = DEBUG_EVENT {
2022 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
2023 panic!("WaitForDebugEvent failed!");
2027 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
2031 if unsafe { ContinueDebugEvent(event.process_id,
2033 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
2034 panic!("ContinueDebugEvent failed!");
2037 assert!(events > 0);
2041 fn test_command_implements_send() {
2042 fn take_send_type<T: Send>(_: T) {}
2043 take_send_type(Command::new(""))