1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A module for working with processes.
13 //! This module is mostly concerned with spawning and interacting with child
14 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
17 //! # Spawning a process
19 //! The [`Command`] struct is used to configure and spawn processes:
22 //! use std::process::Command;
24 //! let output = Command::new("echo")
25 //! .arg("Hello world")
27 //! .expect("Failed to execute command");
29 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
32 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
33 //! to spawn a process. In particular, [`output`] spawns the child process and
34 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
35 //! that represents the spawned child process.
39 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
40 //! configured by passing an [`Stdio`] to the corresponding method on
41 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
42 //! example, piping output from one command into another command can be done
46 //! use std::process::{Command, Stdio};
48 //! // stdout must be configured with `Stdio::piped` in order to use
49 //! // `echo_child.stdout`
50 //! let echo_child = Command::new("echo")
51 //! .arg("Oh no, a tpyo!")
52 //! .stdout(Stdio::piped())
54 //! .expect("Failed to start echo process");
56 //! // Note that `echo_child` is moved here, but we won't be needing
57 //! // `echo_child` anymore
58 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
60 //! let mut sed_child = Command::new("sed")
61 //! .arg("s/tpyo/typo/")
62 //! .stdin(Stdio::from(echo_out))
63 //! .stdout(Stdio::piped())
65 //! .expect("Failed to start sed process");
67 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
68 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
71 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
72 //! [`ChildStdin`] implements [`Write`]:
75 //! use std::process::{Command, Stdio};
76 //! use std::io::Write;
78 //! let mut child = Command::new("/bin/cat")
79 //! .stdin(Stdio::piped())
80 //! .stdout(Stdio::piped())
82 //! .expect("failed to execute child");
85 //! // limited borrow of stdin
86 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
87 //! stdin.write_all(b"test").expect("failed to write to stdin");
90 //! let output = child
91 //! .wait_with_output()
92 //! .expect("failed to wait on child");
94 //! assert_eq!(b"test", output.stdout.as_slice());
97 //! [`abort`]: fn.abort.html
98 //! [`exit`]: fn.exit.html
100 //! [`Command`]: struct.Command.html
101 //! [`spawn`]: struct.Command.html#method.spawn
102 //! [`output`]: struct.Command.html#method.output
104 //! [`Child`]: struct.Child.html
105 //! [`ChildStdin`]: struct.ChildStdin.html
106 //! [`ChildStdout`]: struct.ChildStdout.html
107 //! [`ChildStderr`]: struct.ChildStderr.html
108 //! [`Stdio`]: struct.Stdio.html
110 //! [`stdout`]: struct.Command.html#method.stdout
111 //! [`stdin`]: struct.Command.html#method.stdin
112 //! [`stderr`]: struct.Command.html#method.stderr
114 //! [`Write`]: ../io/trait.Write.html
115 //! [`Read`]: ../io/trait.Read.html
117 #![stable(feature = "process", since = "1.0.0")]
124 use io::{self, Initializer};
127 use sys::pipe::{read2, AnonPipe};
128 use sys::process as imp;
129 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
131 /// Representation of a running or exited child process.
133 /// This structure is used to represent and manage child processes. A child
134 /// process is created via the [`Command`] struct, which configures the
135 /// spawning process and can itself be constructed using a builder-style
138 /// There is no implementation of [`Drop`] for child processes,
139 /// so if you do not ensure the `Child` has exited then it will continue to
140 /// run, even after the `Child` handle to the child process has gone out of
143 /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
144 /// the parent process wait until the child has actually exited before
150 /// use std::process::Command;
152 /// let mut child = Command::new("/bin/cat")
155 /// .expect("failed to execute child");
157 /// let ecode = child.wait()
158 /// .expect("failed to wait on child");
160 /// assert!(ecode.success());
163 /// [`Command`]: struct.Command.html
164 /// [`Drop`]: ../../core/ops/trait.Drop.html
165 /// [`wait`]: #method.wait
166 #[stable(feature = "process", since = "1.0.0")]
168 handle: imp::Process,
170 /// The handle for writing to the child's standard input (stdin), if it has
172 #[stable(feature = "process", since = "1.0.0")]
173 pub stdin: Option<ChildStdin>,
175 /// The handle for reading from the child's standard output (stdout), if it
176 /// has been captured.
177 #[stable(feature = "process", since = "1.0.0")]
178 pub stdout: Option<ChildStdout>,
180 /// The handle for reading from the child's standard error (stderr), if it
181 /// has been captured.
182 #[stable(feature = "process", since = "1.0.0")]
183 pub stderr: Option<ChildStderr>,
186 impl AsInner<imp::Process> for Child {
187 fn as_inner(&self) -> &imp::Process { &self.handle }
190 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
191 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
194 stdin: io.stdin.map(ChildStdin::from_inner),
195 stdout: io.stdout.map(ChildStdout::from_inner),
196 stderr: io.stderr.map(ChildStderr::from_inner),
201 impl IntoInner<imp::Process> for Child {
202 fn into_inner(self) -> imp::Process { self.handle }
205 #[stable(feature = "std_debug", since = "1.16.0")]
206 impl fmt::Debug for Child {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 f.debug_struct("Child")
209 .field("stdin", &self.stdin)
210 .field("stdout", &self.stdout)
211 .field("stderr", &self.stderr)
216 /// A handle to a child process's standard input (stdin).
218 /// This struct is used in the [`stdin`] field on [`Child`].
220 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
221 /// file handle will be closed. If the child process was blocked on input prior
222 /// to being dropped, it will become unblocked after dropping.
224 /// [`Child`]: struct.Child.html
225 /// [`stdin`]: struct.Child.html#structfield.stdin
226 /// [dropped]: ../ops/trait.Drop.html
227 #[stable(feature = "process", since = "1.0.0")]
228 pub struct ChildStdin {
232 #[stable(feature = "process", since = "1.0.0")]
233 impl Write for ChildStdin {
234 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
235 self.inner.write(buf)
238 fn flush(&mut self) -> io::Result<()> {
243 impl AsInner<AnonPipe> for ChildStdin {
244 fn as_inner(&self) -> &AnonPipe { &self.inner }
247 impl IntoInner<AnonPipe> for ChildStdin {
248 fn into_inner(self) -> AnonPipe { self.inner }
251 impl FromInner<AnonPipe> for ChildStdin {
252 fn from_inner(pipe: AnonPipe) -> ChildStdin {
253 ChildStdin { inner: pipe }
257 #[stable(feature = "std_debug", since = "1.16.0")]
258 impl fmt::Debug for ChildStdin {
259 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
260 f.pad("ChildStdin { .. }")
264 /// A handle to a child process's standard output (stdout).
266 /// This struct is used in the [`stdout`] field on [`Child`].
268 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
269 /// underlying file handle will be closed.
271 /// [`Child`]: struct.Child.html
272 /// [`stdout`]: struct.Child.html#structfield.stdout
273 /// [dropped]: ../ops/trait.Drop.html
274 #[stable(feature = "process", since = "1.0.0")]
275 pub struct ChildStdout {
279 #[stable(feature = "process", since = "1.0.0")]
280 impl Read for ChildStdout {
281 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
285 unsafe fn initializer(&self) -> Initializer {
290 impl AsInner<AnonPipe> for ChildStdout {
291 fn as_inner(&self) -> &AnonPipe { &self.inner }
294 impl IntoInner<AnonPipe> for ChildStdout {
295 fn into_inner(self) -> AnonPipe { self.inner }
298 impl FromInner<AnonPipe> for ChildStdout {
299 fn from_inner(pipe: AnonPipe) -> ChildStdout {
300 ChildStdout { inner: pipe }
304 #[stable(feature = "std_debug", since = "1.16.0")]
305 impl fmt::Debug for ChildStdout {
306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307 f.pad("ChildStdout { .. }")
311 /// A handle to a child process's stderr.
313 /// This struct is used in the [`stderr`] field on [`Child`].
315 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
316 /// underlying file handle will be closed.
318 /// [`Child`]: struct.Child.html
319 /// [`stderr`]: struct.Child.html#structfield.stderr
320 /// [dropped]: ../ops/trait.Drop.html
321 #[stable(feature = "process", since = "1.0.0")]
322 pub struct ChildStderr {
326 #[stable(feature = "process", since = "1.0.0")]
327 impl Read for ChildStderr {
328 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
332 unsafe fn initializer(&self) -> Initializer {
337 impl AsInner<AnonPipe> for ChildStderr {
338 fn as_inner(&self) -> &AnonPipe { &self.inner }
341 impl IntoInner<AnonPipe> for ChildStderr {
342 fn into_inner(self) -> AnonPipe { self.inner }
345 impl FromInner<AnonPipe> for ChildStderr {
346 fn from_inner(pipe: AnonPipe) -> ChildStderr {
347 ChildStderr { inner: pipe }
351 #[stable(feature = "std_debug", since = "1.16.0")]
352 impl fmt::Debug for ChildStderr {
353 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
354 f.pad("ChildStderr { .. }")
358 /// A process builder, providing fine-grained control
359 /// over how a new process should be spawned.
361 /// A default configuration can be
362 /// generated using `Command::new(program)`, where `program` gives a path to the
363 /// program to be executed. Additional builder methods allow the configuration
364 /// to be changed (for example, by adding arguments) prior to spawning:
367 /// use std::process::Command;
369 /// let output = if cfg!(target_os = "windows") {
370 /// Command::new("cmd")
371 /// .args(&["/C", "echo hello"])
373 /// .expect("failed to execute process")
375 /// Command::new("sh")
377 /// .arg("echo hello")
379 /// .expect("failed to execute process")
382 /// let hello = output.stdout;
384 #[stable(feature = "process", since = "1.0.0")]
390 /// Constructs a new `Command` for launching the program at
391 /// path `program`, with the following default configuration:
393 /// * No arguments to the program
394 /// * Inherit the current process's environment
395 /// * Inherit the current process's working directory
396 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
398 /// Builder methods are provided to change these defaults and
399 /// otherwise configure the process.
401 /// If `program` is not an absolute path, the `PATH` will be searched in
402 /// an OS-defined way.
404 /// The search path to be used may be controlled by setting the
405 /// `PATH` environment variable on the Command,
406 /// but this has some implementation limitations on Windows
407 /// (see <https://github.com/rust-lang/rust/issues/37519>).
414 /// use std::process::Command;
416 /// Command::new("sh")
418 /// .expect("sh command failed to start");
420 #[stable(feature = "process", since = "1.0.0")]
421 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
422 Command { inner: imp::Command::new(program.as_ref()) }
425 /// Add an argument to pass to the program.
427 /// Only one argument can be passed per use. So instead of:
430 /// # std::process::Command::new("sh")
431 /// .arg("-C /path/to/repo")
438 /// # std::process::Command::new("sh")
440 /// .arg("/path/to/repo")
444 /// To pass multiple arguments see [`args`].
446 /// [`args`]: #method.args
453 /// use std::process::Command;
455 /// Command::new("ls")
459 /// .expect("ls command failed to start");
461 #[stable(feature = "process", since = "1.0.0")]
462 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
463 self.inner.arg(arg.as_ref());
467 /// Add multiple arguments to pass to the program.
469 /// To pass a single argument see [`arg`].
471 /// [`arg`]: #method.arg
478 /// use std::process::Command;
480 /// Command::new("ls")
481 /// .args(&["-l", "-a"])
483 /// .expect("ls command failed to start");
485 #[stable(feature = "process", since = "1.0.0")]
486 pub fn args<I, S>(&mut self, args: I) -> &mut Command
487 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
490 self.arg(arg.as_ref());
495 /// Inserts or updates an environment variable mapping.
497 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
498 /// and case-sensitive on all other platforms.
505 /// use std::process::Command;
507 /// Command::new("ls")
508 /// .env("PATH", "/bin")
510 /// .expect("ls command failed to start");
512 #[stable(feature = "process", since = "1.0.0")]
513 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
514 where K: AsRef<OsStr>, V: AsRef<OsStr>
516 self.inner.env_mut().set(key.as_ref(), val.as_ref());
520 /// Add or update multiple environment variable mappings.
527 /// use std::process::{Command, Stdio};
529 /// use std::collections::HashMap;
531 /// let filtered_env : HashMap<String, String> =
532 /// env::vars().filter(|&(ref k, _)|
533 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
536 /// Command::new("printenv")
537 /// .stdin(Stdio::null())
538 /// .stdout(Stdio::inherit())
540 /// .envs(&filtered_env)
542 /// .expect("printenv failed to start");
544 #[stable(feature = "command_envs", since = "1.19.0")]
545 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
546 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
548 for (ref key, ref val) in vars {
549 self.inner.env_mut().set(key.as_ref(), val.as_ref());
554 /// Removes an environment variable mapping.
561 /// use std::process::Command;
563 /// Command::new("ls")
564 /// .env_remove("PATH")
566 /// .expect("ls command failed to start");
568 #[stable(feature = "process", since = "1.0.0")]
569 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
570 self.inner.env_mut().remove(key.as_ref());
574 /// Clears the entire environment map for the child process.
581 /// use std::process::Command;
583 /// Command::new("ls")
586 /// .expect("ls command failed to start");
588 #[stable(feature = "process", since = "1.0.0")]
589 pub fn env_clear(&mut self) -> &mut Command {
590 self.inner.env_mut().clear();
594 /// Sets the working directory for the child process.
601 /// use std::process::Command;
603 /// Command::new("ls")
604 /// .current_dir("/bin")
606 /// .expect("ls command failed to start");
608 #[stable(feature = "process", since = "1.0.0")]
609 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
610 self.inner.cwd(dir.as_ref().as_ref());
614 /// Configuration for the child process's standard input (stdin) handle.
616 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
617 /// defaults to [`piped`] when used with `output`.
619 /// [`inherit`]: struct.Stdio.html#method.inherit
620 /// [`piped`]: struct.Stdio.html#method.piped
627 /// use std::process::{Command, Stdio};
629 /// Command::new("ls")
630 /// .stdin(Stdio::null())
632 /// .expect("ls command failed to start");
634 #[stable(feature = "process", since = "1.0.0")]
635 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
636 self.inner.stdin(cfg.into().0);
640 /// Configuration for the child process's standard output (stdout) handle.
642 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
643 /// defaults to [`piped`] when used with `output`.
645 /// [`inherit`]: struct.Stdio.html#method.inherit
646 /// [`piped`]: struct.Stdio.html#method.piped
653 /// use std::process::{Command, Stdio};
655 /// Command::new("ls")
656 /// .stdout(Stdio::null())
658 /// .expect("ls command failed to start");
660 #[stable(feature = "process", since = "1.0.0")]
661 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
662 self.inner.stdout(cfg.into().0);
666 /// Configuration for the child process's standard error (stderr) handle.
668 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
669 /// defaults to [`piped`] when used with `output`.
671 /// [`inherit`]: struct.Stdio.html#method.inherit
672 /// [`piped`]: struct.Stdio.html#method.piped
679 /// use std::process::{Command, Stdio};
681 /// Command::new("ls")
682 /// .stderr(Stdio::null())
684 /// .expect("ls command failed to start");
686 #[stable(feature = "process", since = "1.0.0")]
687 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
688 self.inner.stderr(cfg.into().0);
692 /// Executes the command as a child process, returning a handle to it.
694 /// By default, stdin, stdout and stderr are inherited from the parent.
701 /// use std::process::Command;
703 /// Command::new("ls")
705 /// .expect("ls command failed to start");
707 #[stable(feature = "process", since = "1.0.0")]
708 pub fn spawn(&mut self) -> io::Result<Child> {
709 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
712 /// Executes the command as a child process, waiting for it to finish and
713 /// collecting all of its output.
715 /// By default, stdout and stderr are captured (and used to provide the
716 /// resulting output). Stdin is not inherited from the parent and any
717 /// attempt by the child process to read from the stdin stream will result
718 /// in the stream immediately closing.
723 /// use std::process::Command;
724 /// let output = Command::new("/bin/cat")
727 /// .expect("failed to execute process");
729 /// println!("status: {}", output.status);
730 /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
731 /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
733 /// assert!(output.status.success());
735 #[stable(feature = "process", since = "1.0.0")]
736 pub fn output(&mut self) -> io::Result<Output> {
737 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
738 .and_then(|p| p.wait_with_output())
741 /// Executes a command as a child process, waiting for it to finish and
742 /// collecting its exit status.
744 /// By default, stdin, stdout and stderr are inherited from the parent.
749 /// use std::process::Command;
751 /// let status = Command::new("/bin/cat")
754 /// .expect("failed to execute process");
756 /// println!("process exited with: {}", status);
758 /// assert!(status.success());
760 #[stable(feature = "process", since = "1.0.0")]
761 pub fn status(&mut self) -> io::Result<ExitStatus> {
762 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
763 .and_then(|mut p| p.wait())
767 #[stable(feature = "rust1", since = "1.0.0")]
768 impl fmt::Debug for Command {
769 /// Format the program and arguments of a Command for display. Any
770 /// non-utf8 data is lossily converted using the utf8 replacement
772 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777 impl AsInner<imp::Command> for Command {
778 fn as_inner(&self) -> &imp::Command { &self.inner }
781 impl AsInnerMut<imp::Command> for Command {
782 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
785 /// The output of a finished process.
787 /// This is returned in a Result by either the [`output`] method of a
788 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
791 /// [`Command`]: struct.Command.html
792 /// [`Child`]: struct.Child.html
793 /// [`output`]: struct.Command.html#method.output
794 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
795 #[derive(PartialEq, Eq, Clone)]
796 #[stable(feature = "process", since = "1.0.0")]
798 /// The status (exit code) of the process.
799 #[stable(feature = "process", since = "1.0.0")]
800 pub status: ExitStatus,
801 /// The data that the process wrote to stdout.
802 #[stable(feature = "process", since = "1.0.0")]
804 /// The data that the process wrote to stderr.
805 #[stable(feature = "process", since = "1.0.0")]
809 // If either stderr or stdout are valid utf8 strings it prints the valid
810 // strings, otherwise it prints the byte sequence instead
811 #[stable(feature = "process_output_debug", since = "1.7.0")]
812 impl fmt::Debug for Output {
813 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
815 let stdout_utf8 = str::from_utf8(&self.stdout);
816 let stdout_debug: &fmt::Debug = match stdout_utf8 {
818 Err(_) => &self.stdout
821 let stderr_utf8 = str::from_utf8(&self.stderr);
822 let stderr_debug: &fmt::Debug = match stderr_utf8 {
824 Err(_) => &self.stderr
827 fmt.debug_struct("Output")
828 .field("status", &self.status)
829 .field("stdout", stdout_debug)
830 .field("stderr", stderr_debug)
835 /// Describes what to do with a standard I/O stream for a child process when
836 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
838 /// [`stdin`]: struct.Command.html#method.stdin
839 /// [`stdout`]: struct.Command.html#method.stdout
840 /// [`stderr`]: struct.Command.html#method.stderr
841 /// [`Command`]: struct.Command.html
842 #[stable(feature = "process", since = "1.0.0")]
843 pub struct Stdio(imp::Stdio);
846 /// A new pipe should be arranged to connect the parent and child processes.
853 /// use std::process::{Command, Stdio};
855 /// let output = Command::new("echo")
856 /// .arg("Hello, world!")
857 /// .stdout(Stdio::piped())
859 /// .expect("Failed to execute command");
861 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
862 /// // Nothing echoed to console
868 /// use std::io::Write;
869 /// use std::process::{Command, Stdio};
871 /// let mut child = Command::new("rev")
872 /// .stdin(Stdio::piped())
873 /// .stdout(Stdio::piped())
875 /// .expect("Failed to spawn child process");
878 /// let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
879 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
882 /// let output = child.wait_with_output().expect("Failed to read stdout");
883 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
885 #[stable(feature = "process", since = "1.0.0")]
886 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
888 /// The child inherits from the corresponding parent descriptor.
895 /// use std::process::{Command, Stdio};
897 /// let output = Command::new("echo")
898 /// .arg("Hello, world!")
899 /// .stdout(Stdio::inherit())
901 /// .expect("Failed to execute command");
903 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
904 /// // "Hello, world!" echoed to console
910 /// use std::process::{Command, Stdio};
912 /// let output = Command::new("rev")
913 /// .stdin(Stdio::inherit())
914 /// .stdout(Stdio::piped())
916 /// .expect("Failed to execute command");
918 /// println!("You piped in the reverse of: {}", String::from_utf8_lossy(&output.stdout));
920 #[stable(feature = "process", since = "1.0.0")]
921 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
923 /// This stream will be ignored. This is the equivalent of attaching the
924 /// stream to `/dev/null`
931 /// use std::process::{Command, Stdio};
933 /// let output = Command::new("echo")
934 /// .arg("Hello, world!")
935 /// .stdout(Stdio::null())
937 /// .expect("Failed to execute command");
939 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
940 /// // Nothing echoed to console
946 /// use std::process::{Command, Stdio};
948 /// let output = Command::new("rev")
949 /// .stdin(Stdio::null())
950 /// .stdout(Stdio::piped())
952 /// .expect("Failed to execute command");
954 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
955 /// // Ignores any piped-in input
957 #[stable(feature = "process", since = "1.0.0")]
958 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
961 impl FromInner<imp::Stdio> for Stdio {
962 fn from_inner(inner: imp::Stdio) -> Stdio {
967 #[stable(feature = "std_debug", since = "1.16.0")]
968 impl fmt::Debug for Stdio {
969 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
970 f.pad("Stdio { .. }")
974 #[stable(feature = "stdio_from", since = "1.20.0")]
975 impl From<ChildStdin> for Stdio {
976 fn from(child: ChildStdin) -> Stdio {
977 Stdio::from_inner(child.into_inner().into())
981 #[stable(feature = "stdio_from", since = "1.20.0")]
982 impl From<ChildStdout> for Stdio {
983 fn from(child: ChildStdout) -> Stdio {
984 Stdio::from_inner(child.into_inner().into())
988 #[stable(feature = "stdio_from", since = "1.20.0")]
989 impl From<ChildStderr> for Stdio {
990 fn from(child: ChildStderr) -> Stdio {
991 Stdio::from_inner(child.into_inner().into())
995 #[stable(feature = "stdio_from", since = "1.20.0")]
996 impl From<fs::File> for Stdio {
997 fn from(file: fs::File) -> Stdio {
998 Stdio::from_inner(file.into_inner().into())
1002 /// Describes the result of a process after it has terminated.
1004 /// This `struct` is used to represent the exit status of a child process.
1005 /// Child processes are created via the [`Command`] struct and their exit
1006 /// status is exposed through the [`status`] method.
1008 /// [`Command`]: struct.Command.html
1009 /// [`status`]: struct.Command.html#method.status
1010 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1011 #[stable(feature = "process", since = "1.0.0")]
1012 pub struct ExitStatus(imp::ExitStatus);
1015 /// Was termination successful? Signal termination is not considered a
1016 /// success, and success is defined as a zero exit status.
1021 /// use std::process::Command;
1023 /// let status = Command::new("mkdir")
1024 /// .arg("projects")
1026 /// .expect("failed to execute mkdir");
1028 /// if status.success() {
1029 /// println!("'projects/' directory created");
1031 /// println!("failed to create 'projects/' directory");
1034 #[stable(feature = "process", since = "1.0.0")]
1035 pub fn success(&self) -> bool {
1039 /// Returns the exit code of the process, if any.
1041 /// On Unix, this will return `None` if the process was terminated
1042 /// by a signal; `std::os::unix` provides an extension trait for
1043 /// extracting the signal and other details from the `ExitStatus`.
1048 /// use std::process::Command;
1050 /// let status = Command::new("mkdir")
1051 /// .arg("projects")
1053 /// .expect("failed to execute mkdir");
1055 /// match status.code() {
1056 /// Some(code) => println!("Exited with status code: {}", code),
1057 /// None => println!("Process terminated by signal")
1060 #[stable(feature = "process", since = "1.0.0")]
1061 pub fn code(&self) -> Option<i32> {
1066 impl AsInner<imp::ExitStatus> for ExitStatus {
1067 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
1070 impl FromInner<imp::ExitStatus> for ExitStatus {
1071 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1076 #[stable(feature = "process", since = "1.0.0")]
1077 impl fmt::Display for ExitStatus {
1078 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1084 /// Forces the child to exit. This is equivalent to sending a
1085 /// SIGKILL on unix platforms.
1092 /// use std::process::Command;
1094 /// let mut command = Command::new("yes");
1095 /// if let Ok(mut child) = command.spawn() {
1096 /// child.kill().expect("command wasn't running");
1098 /// println!("yes command didn't start");
1101 #[stable(feature = "process", since = "1.0.0")]
1102 pub fn kill(&mut self) -> io::Result<()> {
1106 /// Returns the OS-assigned process identifier associated with this child.
1113 /// use std::process::Command;
1115 /// let mut command = Command::new("ls");
1116 /// if let Ok(child) = command.spawn() {
1117 /// println!("Child's id is {}", child.id());
1119 /// println!("ls command didn't start");
1122 #[stable(feature = "process_id", since = "1.3.0")]
1123 pub fn id(&self) -> u32 {
1127 /// Waits for the child to exit completely, returning the status that it
1128 /// exited with. This function will continue to have the same return value
1129 /// after it has been called at least once.
1131 /// The stdin handle to the child process, if any, will be closed
1132 /// before waiting. This helps avoid deadlock: it ensures that the
1133 /// child does not block waiting for input from the parent, while
1134 /// the parent waits for the child to exit.
1141 /// use std::process::Command;
1143 /// let mut command = Command::new("ls");
1144 /// if let Ok(mut child) = command.spawn() {
1145 /// child.wait().expect("command wasn't running");
1146 /// println!("Child has finished its execution!");
1148 /// println!("ls command didn't start");
1151 #[stable(feature = "process", since = "1.0.0")]
1152 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1153 drop(self.stdin.take());
1154 self.handle.wait().map(ExitStatus)
1157 /// Attempts to collect the exit status of the child if it has already
1160 /// This function will not block the calling thread and will only advisorily
1161 /// check to see if the child process has exited or not. If the child has
1162 /// exited then on Unix the process id is reaped. This function is
1163 /// guaranteed to repeatedly return a successful exit status so long as the
1164 /// child has already exited.
1166 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1167 /// exit status is not available at this time then `Ok(None)` is returned.
1168 /// If an error occurs, then that error is returned.
1170 /// Note that unlike `wait`, this function will not attempt to drop stdin.
1177 /// use std::process::Command;
1179 /// let mut child = Command::new("ls").spawn().unwrap();
1181 /// match child.try_wait() {
1182 /// Ok(Some(status)) => println!("exited with: {}", status),
1184 /// println!("status not ready yet, let's really wait");
1185 /// let res = child.wait();
1186 /// println!("result: {:?}", res);
1188 /// Err(e) => println!("error attempting to wait: {}", e),
1191 #[stable(feature = "process_try_wait", since = "1.18.0")]
1192 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1193 Ok(self.handle.try_wait()?.map(ExitStatus))
1196 /// Simultaneously waits for the child to exit and collect all remaining
1197 /// output on the stdout/stderr handles, returning an `Output`
1200 /// The stdin handle to the child process, if any, will be closed
1201 /// before waiting. This helps avoid deadlock: it ensures that the
1202 /// child does not block waiting for input from the parent, while
1203 /// the parent waits for the child to exit.
1205 /// By default, stdin, stdout and stderr are inherited from the parent.
1206 /// In order to capture the output into this `Result<Output>` it is
1207 /// necessary to create new pipes between parent and child. Use
1208 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1213 /// use std::process::{Command, Stdio};
1215 /// let child = Command::new("/bin/cat")
1216 /// .arg("file.txt")
1217 /// .stdout(Stdio::piped())
1219 /// .expect("failed to execute child");
1221 /// let output = child
1222 /// .wait_with_output()
1223 /// .expect("failed to wait on child");
1225 /// assert!(output.status.success());
1228 #[stable(feature = "process", since = "1.0.0")]
1229 pub fn wait_with_output(mut self) -> io::Result<Output> {
1230 drop(self.stdin.take());
1232 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1233 match (self.stdout.take(), self.stderr.take()) {
1235 (Some(mut out), None) => {
1236 let res = out.read_to_end(&mut stdout);
1239 (None, Some(mut err)) => {
1240 let res = err.read_to_end(&mut stderr);
1243 (Some(out), Some(err)) => {
1244 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1249 let status = self.wait()?;
1258 /// Terminates the current process with the specified exit code.
1260 /// This function will never return and will immediately terminate the current
1261 /// process. The exit code is passed through to the underlying OS and will be
1262 /// available for consumption by another process.
1264 /// Note that because this function never returns, and that it terminates the
1265 /// process, no destructors on the current stack or any other thread's stack
1266 /// will be run. If a clean shutdown is needed it is recommended to only call
1267 /// this function at a known point where there are no more destructors left
1270 /// ## Platform-specific behavior
1272 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1273 /// will be visible to a parent process inspecting the exit code. On most
1274 /// Unix-like platforms, only the eight least-significant bits are considered.
1278 /// Due to this function’s behavior regarding destructors, a conventional way
1279 /// to use the function is to extract the actual computation to another
1280 /// function and compute the exit code from its return value:
1283 /// fn run_app() -> Result<(), ()> {
1284 /// // Application logic here
1289 /// ::std::process::exit(match run_app() {
1292 /// eprintln!("error: {:?}", err);
1299 /// Due to [platform-specific behavior], the exit code for this example will be
1300 /// `0` on Linux, but `256` on Windows:
1303 /// use std::process;
1305 /// process::exit(0x0100);
1308 /// [platform-specific behavior]: #platform-specific-behavior
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 pub fn exit(code: i32) -> ! {
1311 ::sys_common::cleanup();
1312 ::sys::os::exit(code)
1315 /// Terminates the process in an abnormal fashion.
1317 /// The function will never return and will immediately terminate the current
1318 /// process in a platform specific "abnormal" manner.
1320 /// Note that because this function never returns, and that it terminates the
1321 /// process, no destructors on the current stack or any other thread's stack
1324 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1325 /// the current thread's stack and calls all destructors.
1326 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1327 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1328 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1330 /// If a clean shutdown is needed it is recommended to only call
1331 /// this function at a known point where there are no more destructors left
1337 /// use std::process;
1340 /// println!("aborting");
1342 /// process::abort();
1344 /// // execution never gets here
1348 /// The `abort` function terminates the process, so the destructor will not
1349 /// get run on the example below:
1352 /// use std::process;
1356 /// impl Drop for HasDrop {
1357 /// fn drop(&mut self) {
1358 /// println!("This will never be printed!");
1363 /// let _x = HasDrop;
1364 /// process::abort();
1365 /// // the destructor implemented for HasDrop will never get run
1369 /// [`panic!`]: ../../std/macro.panic.html
1370 /// [panic hook]: ../../std/panic/fn.set_hook.html
1371 #[stable(feature = "process_abort", since = "1.17.0")]
1372 pub fn abort() -> ! {
1373 unsafe { ::sys::abort_internal() };
1376 /// Returns the OS-assigned process identifier associated with this process.
1383 /// #![feature(getpid)]
1384 /// use std::process;
1386 /// println!("My pid is {}", process::id());
1390 #[unstable(feature = "getpid", issue = "44971", reason = "recently added")]
1391 pub fn id() -> u32 {
1395 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
1401 use super::{Command, Output, Stdio};
1403 // FIXME(#10380) these tests should not all be ignored on android.
1406 #[cfg_attr(target_os = "android", ignore)]
1408 let p = if cfg!(target_os = "windows") {
1409 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1411 Command::new("true").spawn()
1414 let mut p = p.unwrap();
1415 assert!(p.wait().unwrap().success());
1419 #[cfg_attr(target_os = "android", ignore)]
1420 fn smoke_failure() {
1421 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1428 #[cfg_attr(target_os = "android", ignore)]
1429 fn exit_reported_right() {
1430 let p = if cfg!(target_os = "windows") {
1431 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1433 Command::new("false").spawn()
1436 let mut p = p.unwrap();
1437 assert!(p.wait().unwrap().code() == Some(1));
1443 #[cfg_attr(target_os = "android", ignore)]
1444 fn signal_reported_right() {
1445 use os::unix::process::ExitStatusExt;
1447 let mut p = Command::new("/bin/sh")
1448 .arg("-c").arg("read a")
1449 .stdin(Stdio::piped())
1452 match p.wait().unwrap().signal() {
1454 result => panic!("not terminated by signal 9 (instead, {:?})",
1459 pub fn run_output(mut cmd: Command) -> String {
1460 let p = cmd.spawn();
1462 let mut p = p.unwrap();
1463 assert!(p.stdout.is_some());
1464 let mut ret = String::new();
1465 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1466 assert!(p.wait().unwrap().success());
1471 #[cfg_attr(target_os = "android", ignore)]
1473 if cfg!(target_os = "windows") {
1474 let mut cmd = Command::new("cmd");
1475 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1476 assert_eq!(run_output(cmd), "foobar\r\n");
1478 let mut cmd = Command::new("echo");
1479 cmd.arg("foobar").stdout(Stdio::piped());
1480 assert_eq!(run_output(cmd), "foobar\n");
1485 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1486 fn set_current_dir_works() {
1487 let mut cmd = Command::new("/bin/sh");
1488 cmd.arg("-c").arg("pwd")
1490 .stdout(Stdio::piped());
1491 assert_eq!(run_output(cmd), "/\n");
1495 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1497 let mut p = Command::new("/bin/sh")
1498 .arg("-c").arg("read line; echo $line")
1499 .stdin(Stdio::piped())
1500 .stdout(Stdio::piped())
1502 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1503 drop(p.stdin.take());
1504 let mut out = String::new();
1505 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1506 assert!(p.wait().unwrap().success());
1507 assert_eq!(out, "foobar\n");
1512 #[cfg_attr(target_os = "android", ignore)]
1515 use os::unix::prelude::*;
1517 let mut p = Command::new("/bin/sh")
1518 .arg("-c").arg("true")
1519 .uid(unsafe { libc::getuid() })
1520 .gid(unsafe { libc::getgid() })
1522 assert!(p.wait().unwrap().success());
1526 #[cfg_attr(target_os = "android", ignore)]
1528 fn uid_to_root_fails() {
1529 use os::unix::prelude::*;
1532 // if we're already root, this isn't a valid test. Most of the bots run
1533 // as non-root though (android is an exception).
1534 if unsafe { libc::getuid() == 0 } { return }
1535 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1539 #[cfg_attr(target_os = "android", ignore)]
1540 fn test_process_status() {
1541 let mut status = if cfg!(target_os = "windows") {
1542 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1544 Command::new("false").status().unwrap()
1546 assert!(status.code() == Some(1));
1548 status = if cfg!(target_os = "windows") {
1549 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1551 Command::new("true").status().unwrap()
1553 assert!(status.success());
1557 fn test_process_output_fail_to_start() {
1558 match Command::new("/no-binary-by-this-name-should-exist").output() {
1559 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1565 #[cfg_attr(target_os = "android", ignore)]
1566 fn test_process_output_output() {
1567 let Output {status, stdout, stderr}
1568 = if cfg!(target_os = "windows") {
1569 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1571 Command::new("echo").arg("hello").output().unwrap()
1573 let output_str = str::from_utf8(&stdout).unwrap();
1575 assert!(status.success());
1576 assert_eq!(output_str.trim().to_string(), "hello");
1577 assert_eq!(stderr, Vec::new());
1581 #[cfg_attr(target_os = "android", ignore)]
1582 fn test_process_output_error() {
1583 let Output {status, stdout, stderr}
1584 = if cfg!(target_os = "windows") {
1585 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1587 Command::new("mkdir").arg("./").output().unwrap()
1590 assert!(status.code() == Some(1));
1591 assert_eq!(stdout, Vec::new());
1592 assert!(!stderr.is_empty());
1596 #[cfg_attr(target_os = "android", ignore)]
1597 fn test_finish_once() {
1598 let mut prog = if cfg!(target_os = "windows") {
1599 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1601 Command::new("false").spawn().unwrap()
1603 assert!(prog.wait().unwrap().code() == Some(1));
1607 #[cfg_attr(target_os = "android", ignore)]
1608 fn test_finish_twice() {
1609 let mut prog = if cfg!(target_os = "windows") {
1610 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1612 Command::new("false").spawn().unwrap()
1614 assert!(prog.wait().unwrap().code() == Some(1));
1615 assert!(prog.wait().unwrap().code() == Some(1));
1619 #[cfg_attr(target_os = "android", ignore)]
1620 fn test_wait_with_output_once() {
1621 let prog = if cfg!(target_os = "windows") {
1622 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1624 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1627 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1628 let output_str = str::from_utf8(&stdout).unwrap();
1630 assert!(status.success());
1631 assert_eq!(output_str.trim().to_string(), "hello");
1632 assert_eq!(stderr, Vec::new());
1635 #[cfg(all(unix, not(target_os="android")))]
1636 pub fn env_cmd() -> Command {
1639 #[cfg(target_os="android")]
1640 pub fn env_cmd() -> Command {
1641 let mut cmd = Command::new("/system/bin/sh");
1642 cmd.arg("-c").arg("set");
1647 pub fn env_cmd() -> Command {
1648 let mut cmd = Command::new("cmd");
1649 cmd.arg("/c").arg("set");
1654 fn test_inherit_env() {
1657 let result = env_cmd().output().unwrap();
1658 let output = String::from_utf8(result.stdout).unwrap();
1660 for (ref k, ref v) in env::vars() {
1661 // Don't check android RANDOM variable which seems to change
1662 // whenever the shell runs, and our `env_cmd` is indeed running a
1663 // shell which means it'll get a different RANDOM than we probably
1666 // Also skip env vars with `-` in the name on android because, well,
1667 // I'm not sure. It appears though that the `set` command above does
1668 // not print env vars with `-` in the name, so we just skip them
1669 // here as we won't find them in the output. Note that most env vars
1670 // use `_` instead of `-`, but our build system sets a few env vars
1671 // with `-` in the name.
1672 if cfg!(target_os = "android") &&
1673 (*k == "RANDOM" || k.contains("-")) {
1677 // Windows has hidden environment variables whose names start with
1678 // equals signs (`=`). Those do not show up in the output of the
1680 assert!((cfg!(windows) && k.starts_with("=")) ||
1681 k.starts_with("DYLD") ||
1682 output.contains(&format!("{}={}", *k, *v)) ||
1683 output.contains(&format!("{}='{}'", *k, *v)),
1684 "output doesn't contain `{}={}`\n{}",
1690 fn test_override_env() {
1693 // In some build environments (such as chrooted Nix builds), `env` can
1694 // only be found in the explicitly-provided PATH env variable, not in
1695 // default places such as /bin or /usr/bin. So we need to pass through
1696 // PATH to our sub-process.
1697 let mut cmd = env_cmd();
1698 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1699 if let Some(p) = env::var_os("PATH") {
1700 cmd.env("PATH", &p);
1702 let result = cmd.output().unwrap();
1703 let output = String::from_utf8_lossy(&result.stdout).to_string();
1705 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1706 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1710 fn test_add_to_env() {
1711 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1712 let output = String::from_utf8_lossy(&result.stdout).to_string();
1714 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1715 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1719 fn test_capture_env_at_spawn() {
1722 let mut cmd = env_cmd();
1723 cmd.env("RUN_TEST_NEW_ENV1", "123");
1725 // This variable will not be present if the environment has already
1726 // been captured above.
1727 env::set_var("RUN_TEST_NEW_ENV2", "456");
1728 let result = cmd.output().unwrap();
1729 env::remove_var("RUN_TEST_NEW_ENV2");
1731 let output = String::from_utf8_lossy(&result.stdout).to_string();
1733 assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1734 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1735 assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1736 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1739 // Regression tests for #30858.
1741 fn test_interior_nul_in_progname_is_error() {
1742 match Command::new("has-some-\0\0s-inside").spawn() {
1743 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1749 fn test_interior_nul_in_arg_is_error() {
1750 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1751 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1757 fn test_interior_nul_in_args_is_error() {
1758 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1759 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1765 fn test_interior_nul_in_current_dir_is_error() {
1766 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1767 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1772 // Regression tests for #30862.
1774 fn test_interior_nul_in_env_key_is_error() {
1775 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1776 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1782 fn test_interior_nul_in_env_value_is_error() {
1783 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1784 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1789 /// Test that process creation flags work by debugging a process.
1790 /// Other creation flags make it hard or impossible to detect
1791 /// behavioral changes in the process.
1794 fn test_creation_flags() {
1795 use os::windows::process::CommandExt;
1796 use sys::c::{BOOL, DWORD, INFINITE};
1798 struct DEBUG_EVENT {
1799 pub event_code: DWORD,
1800 pub process_id: DWORD,
1801 pub thread_id: DWORD,
1802 // This is a union in the real struct, but we don't
1803 // need this data for the purposes of this test.
1804 pub _junk: [u8; 164],
1808 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1809 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1810 dwContinueStatus: DWORD) -> BOOL;
1813 const DEBUG_PROCESS: DWORD = 1;
1814 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1815 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1817 let mut child = Command::new("cmd")
1818 .creation_flags(DEBUG_PROCESS)
1819 .stdin(Stdio::piped()).spawn().unwrap();
1820 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1822 let mut event = DEBUG_EVENT {
1829 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1830 panic!("WaitForDebugEvent failed!");
1834 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1838 if unsafe { ContinueDebugEvent(event.process_id,
1840 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1841 panic!("ContinueDebugEvent failed!");
1844 assert!(events > 0);
1848 fn test_command_implements_send() {
1849 fn take_send_type<T: Send>(_: T) {}
1850 take_send_type(Command::new(""))