]> git.lizzy.rs Git - rust.git/blob - src/libstd/process.rs
run EndRegion when unwinding otherwise-empty scopes
[rust.git] / src / libstd / process.rs
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.
4 //
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.
10
11 //! A module for working with processes.
12 //!
13 //! # Examples
14 //!
15 //! Basic usage where we try to execute the `cat` shell command:
16 //!
17 //! ```should_panic
18 //! use std::process::Command;
19 //!
20 //! let mut child = Command::new("/bin/cat")
21 //!                         .arg("file.txt")
22 //!                         .spawn()
23 //!                         .expect("failed to execute child");
24 //!
25 //! let ecode = child.wait()
26 //!                  .expect("failed to wait on child");
27 //!
28 //! assert!(ecode.success());
29 //! ```
30 //!
31 //! Calling a command with input and reading its output:
32 //!
33 //! ```no_run
34 //! use std::process::{Command, Stdio};
35 //! use std::io::Write;
36 //!
37 //! let mut child = Command::new("/bin/cat")
38 //!     .stdin(Stdio::piped())
39 //!     .stdout(Stdio::piped())
40 //!     .spawn()
41 //!     .expect("failed to execute child");
42 //!
43 //! {
44 //!     // limited borrow of stdin
45 //!     let stdin = child.stdin.as_mut().expect("failed to get stdin");
46 //!     stdin.write_all(b"test").expect("failed to write to stdin");
47 //! }
48 //!
49 //! let output = child
50 //!     .wait_with_output()
51 //!     .expect("failed to wait on child");
52 //!
53 //! assert_eq!(b"test", output.stdout.as_slice());
54 //! ```
55
56 #![stable(feature = "process", since = "1.0.0")]
57
58 use io::prelude::*;
59
60 use ffi::OsStr;
61 use fmt;
62 use fs;
63 use io::{self, Initializer};
64 use path::Path;
65 use str;
66 use sys::pipe::{read2, AnonPipe};
67 use sys::process as imp;
68 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
69
70 /// Representation of a running or exited child process.
71 ///
72 /// This structure is used to represent and manage child processes. A child
73 /// process is created via the [`Command`] struct, which configures the
74 /// spawning process and can itself be constructed using a builder-style
75 /// interface.
76 ///
77 /// There is no implementation of [`Drop`] for child processes,
78 /// so if you do not ensure the `Child` has exited then it will continue to
79 /// run, even after the `Child` handle to the child process has gone out of
80 /// scope.
81 ///
82 /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
83 /// the parent process wait until the child has actually exited before
84 /// continuing.
85 ///
86 /// # Examples
87 ///
88 /// ```should_panic
89 /// use std::process::Command;
90 ///
91 /// let mut child = Command::new("/bin/cat")
92 ///                         .arg("file.txt")
93 ///                         .spawn()
94 ///                         .expect("failed to execute child");
95 ///
96 /// let ecode = child.wait()
97 ///                  .expect("failed to wait on child");
98 ///
99 /// assert!(ecode.success());
100 /// ```
101 ///
102 /// [`Command`]: struct.Command.html
103 /// [`Drop`]: ../../core/ops/trait.Drop.html
104 /// [`wait`]: #method.wait
105 #[stable(feature = "process", since = "1.0.0")]
106 pub struct Child {
107     handle: imp::Process,
108
109     /// The handle for writing to the child's standard input (stdin), if it has
110     /// been captured.
111     #[stable(feature = "process", since = "1.0.0")]
112     pub stdin: Option<ChildStdin>,
113
114     /// The handle for reading from the child's standard output (stdout), if it
115     /// has been captured.
116     #[stable(feature = "process", since = "1.0.0")]
117     pub stdout: Option<ChildStdout>,
118
119     /// The handle for reading from the child's standard error (stderr), if it
120     /// has been captured.
121     #[stable(feature = "process", since = "1.0.0")]
122     pub stderr: Option<ChildStderr>,
123 }
124
125 impl AsInner<imp::Process> for Child {
126     fn as_inner(&self) -> &imp::Process { &self.handle }
127 }
128
129 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
130     fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
131         Child {
132             handle,
133             stdin: io.stdin.map(ChildStdin::from_inner),
134             stdout: io.stdout.map(ChildStdout::from_inner),
135             stderr: io.stderr.map(ChildStderr::from_inner),
136         }
137     }
138 }
139
140 impl IntoInner<imp::Process> for Child {
141     fn into_inner(self) -> imp::Process { self.handle }
142 }
143
144 #[stable(feature = "std_debug", since = "1.16.0")]
145 impl fmt::Debug for Child {
146     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147         f.debug_struct("Child")
148             .field("stdin", &self.stdin)
149             .field("stdout", &self.stdout)
150             .field("stderr", &self.stderr)
151             .finish()
152     }
153 }
154
155 /// A handle to a child process's standard input (stdin).
156 ///
157 /// This struct is used in the [`stdin`] field on [`Child`].
158 ///
159 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
160 /// file handle will be closed. If the child process was blocked on input prior
161 /// to being dropped, it will become unblocked after dropping.
162 ///
163 /// [`Child`]: struct.Child.html
164 /// [`stdin`]: struct.Child.html#structfield.stdin
165 /// [dropped]: ../ops/trait.Drop.html
166 #[stable(feature = "process", since = "1.0.0")]
167 pub struct ChildStdin {
168     inner: AnonPipe
169 }
170
171 #[stable(feature = "process", since = "1.0.0")]
172 impl Write for ChildStdin {
173     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
174         self.inner.write(buf)
175     }
176
177     fn flush(&mut self) -> io::Result<()> {
178         Ok(())
179     }
180 }
181
182 impl AsInner<AnonPipe> for ChildStdin {
183     fn as_inner(&self) -> &AnonPipe { &self.inner }
184 }
185
186 impl IntoInner<AnonPipe> for ChildStdin {
187     fn into_inner(self) -> AnonPipe { self.inner }
188 }
189
190 impl FromInner<AnonPipe> for ChildStdin {
191     fn from_inner(pipe: AnonPipe) -> ChildStdin {
192         ChildStdin { inner: pipe }
193     }
194 }
195
196 #[stable(feature = "std_debug", since = "1.16.0")]
197 impl fmt::Debug for ChildStdin {
198     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199         f.pad("ChildStdin { .. }")
200     }
201 }
202
203 /// A handle to a child process's standard output (stdout).
204 ///
205 /// This struct is used in the [`stdout`] field on [`Child`].
206 ///
207 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
208 /// underlying file handle will be closed.
209 ///
210 /// [`Child`]: struct.Child.html
211 /// [`stdout`]: struct.Child.html#structfield.stdout
212 /// [dropped]: ../ops/trait.Drop.html
213 #[stable(feature = "process", since = "1.0.0")]
214 pub struct ChildStdout {
215     inner: AnonPipe
216 }
217
218 #[stable(feature = "process", since = "1.0.0")]
219 impl Read for ChildStdout {
220     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
221         self.inner.read(buf)
222     }
223     #[inline]
224     unsafe fn initializer(&self) -> Initializer {
225         Initializer::nop()
226     }
227 }
228
229 impl AsInner<AnonPipe> for ChildStdout {
230     fn as_inner(&self) -> &AnonPipe { &self.inner }
231 }
232
233 impl IntoInner<AnonPipe> for ChildStdout {
234     fn into_inner(self) -> AnonPipe { self.inner }
235 }
236
237 impl FromInner<AnonPipe> for ChildStdout {
238     fn from_inner(pipe: AnonPipe) -> ChildStdout {
239         ChildStdout { inner: pipe }
240     }
241 }
242
243 #[stable(feature = "std_debug", since = "1.16.0")]
244 impl fmt::Debug for ChildStdout {
245     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
246         f.pad("ChildStdout { .. }")
247     }
248 }
249
250 /// A handle to a child process's stderr.
251 ///
252 /// This struct is used in the [`stderr`] field on [`Child`].
253 ///
254 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
255 /// underlying file handle will be closed.
256 ///
257 /// [`Child`]: struct.Child.html
258 /// [`stderr`]: struct.Child.html#structfield.stderr
259 /// [dropped]: ../ops/trait.Drop.html
260 #[stable(feature = "process", since = "1.0.0")]
261 pub struct ChildStderr {
262     inner: AnonPipe
263 }
264
265 #[stable(feature = "process", since = "1.0.0")]
266 impl Read for ChildStderr {
267     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
268         self.inner.read(buf)
269     }
270     #[inline]
271     unsafe fn initializer(&self) -> Initializer {
272         Initializer::nop()
273     }
274 }
275
276 impl AsInner<AnonPipe> for ChildStderr {
277     fn as_inner(&self) -> &AnonPipe { &self.inner }
278 }
279
280 impl IntoInner<AnonPipe> for ChildStderr {
281     fn into_inner(self) -> AnonPipe { self.inner }
282 }
283
284 impl FromInner<AnonPipe> for ChildStderr {
285     fn from_inner(pipe: AnonPipe) -> ChildStderr {
286         ChildStderr { inner: pipe }
287     }
288 }
289
290 #[stable(feature = "std_debug", since = "1.16.0")]
291 impl fmt::Debug for ChildStderr {
292     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293         f.pad("ChildStderr { .. }")
294     }
295 }
296
297 /// A process builder, providing fine-grained control
298 /// over how a new process should be spawned.
299 ///
300 /// A default configuration can be
301 /// generated using `Command::new(program)`, where `program` gives a path to the
302 /// program to be executed. Additional builder methods allow the configuration
303 /// to be changed (for example, by adding arguments) prior to spawning:
304 ///
305 /// ```
306 /// use std::process::Command;
307 ///
308 /// let output = if cfg!(target_os = "windows") {
309 ///     Command::new("cmd")
310 ///             .args(&["/C", "echo hello"])
311 ///             .output()
312 ///             .expect("failed to execute process")
313 /// } else {
314 ///     Command::new("sh")
315 ///             .arg("-c")
316 ///             .arg("echo hello")
317 ///             .output()
318 ///             .expect("failed to execute process")
319 /// };
320 ///
321 /// let hello = output.stdout;
322 /// ```
323 #[stable(feature = "process", since = "1.0.0")]
324 pub struct Command {
325     inner: imp::Command,
326 }
327
328 impl Command {
329     /// Constructs a new `Command` for launching the program at
330     /// path `program`, with the following default configuration:
331     ///
332     /// * No arguments to the program
333     /// * Inherit the current process's environment
334     /// * Inherit the current process's working directory
335     /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
336     ///
337     /// Builder methods are provided to change these defaults and
338     /// otherwise configure the process.
339     ///
340     /// If `program` is not an absolute path, the `PATH` will be searched in
341     /// an OS-defined way.
342     ///
343     /// The search path to be used may be controlled by setting the
344     /// `PATH` environment variable on the Command,
345     /// but this has some implementation limitations on Windows
346     /// (see https://github.com/rust-lang/rust/issues/37519).
347     ///
348     /// # Examples
349     ///
350     /// Basic usage:
351     ///
352     /// ```no_run
353     /// use std::process::Command;
354     ///
355     /// Command::new("sh")
356     ///         .spawn()
357     ///         .expect("sh command failed to start");
358     /// ```
359     #[stable(feature = "process", since = "1.0.0")]
360     pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
361         Command { inner: imp::Command::new(program.as_ref()) }
362     }
363
364     /// Add an argument to pass to the program.
365     ///
366     /// Only one argument can be passed per use. So instead of:
367     ///
368     /// ```no_run
369     /// # std::process::Command::new("sh")
370     /// .arg("-C /path/to/repo")
371     /// # ;
372     /// ```
373     ///
374     /// usage would be:
375     ///
376     /// ```no_run
377     /// # std::process::Command::new("sh")
378     /// .arg("-C")
379     /// .arg("/path/to/repo")
380     /// # ;
381     /// ```
382     ///
383     /// To pass multiple arguments see [`args`].
384     ///
385     /// [`args`]: #method.args
386     ///
387     /// # Examples
388     ///
389     /// Basic usage:
390     ///
391     /// ```no_run
392     /// use std::process::Command;
393     ///
394     /// Command::new("ls")
395     ///         .arg("-l")
396     ///         .arg("-a")
397     ///         .spawn()
398     ///         .expect("ls command failed to start");
399     /// ```
400     #[stable(feature = "process", since = "1.0.0")]
401     pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
402         self.inner.arg(arg.as_ref());
403         self
404     }
405
406     /// Add multiple arguments to pass to the program.
407     ///
408     /// To pass a single argument see [`arg`].
409     ///
410     /// [`arg`]: #method.arg
411     ///
412     /// # Examples
413     ///
414     /// Basic usage:
415     ///
416     /// ```no_run
417     /// use std::process::Command;
418     ///
419     /// Command::new("ls")
420     ///         .args(&["-l", "-a"])
421     ///         .spawn()
422     ///         .expect("ls command failed to start");
423     /// ```
424     #[stable(feature = "process", since = "1.0.0")]
425     pub fn args<I, S>(&mut self, args: I) -> &mut Command
426         where I: IntoIterator<Item=S>, S: AsRef<OsStr>
427     {
428         for arg in args {
429             self.arg(arg.as_ref());
430         }
431         self
432     }
433
434     /// Inserts or updates an environment variable mapping.
435     ///
436     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
437     /// and case-sensitive on all other platforms.
438     ///
439     /// # Examples
440     ///
441     /// Basic usage:
442     ///
443     /// ```no_run
444     /// use std::process::Command;
445     ///
446     /// Command::new("ls")
447     ///         .env("PATH", "/bin")
448     ///         .spawn()
449     ///         .expect("ls command failed to start");
450     /// ```
451     #[stable(feature = "process", since = "1.0.0")]
452     pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
453         where K: AsRef<OsStr>, V: AsRef<OsStr>
454     {
455         self.inner.env(key.as_ref(), val.as_ref());
456         self
457     }
458
459     /// Add or update multiple environment variable mappings.
460     ///
461     /// # Examples
462     ///
463     /// Basic usage:
464     ///
465     /// ```no_run
466     /// use std::process::{Command, Stdio};
467     /// use std::env;
468     /// use std::collections::HashMap;
469     ///
470     /// let filtered_env : HashMap<String, String> =
471     ///     env::vars().filter(|&(ref k, _)|
472     ///         k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
473     ///     ).collect();
474     ///
475     /// Command::new("printenv")
476     ///         .stdin(Stdio::null())
477     ///         .stdout(Stdio::inherit())
478     ///         .env_clear()
479     ///         .envs(&filtered_env)
480     ///         .spawn()
481     ///         .expect("printenv failed to start");
482     /// ```
483     #[stable(feature = "command_envs", since = "1.19.0")]
484     pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
485         where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
486     {
487         for (ref key, ref val) in vars {
488             self.inner.env(key.as_ref(), val.as_ref());
489         }
490         self
491     }
492
493     /// Removes an environment variable mapping.
494     ///
495     /// # Examples
496     ///
497     /// Basic usage:
498     ///
499     /// ```no_run
500     /// use std::process::Command;
501     ///
502     /// Command::new("ls")
503     ///         .env_remove("PATH")
504     ///         .spawn()
505     ///         .expect("ls command failed to start");
506     /// ```
507     #[stable(feature = "process", since = "1.0.0")]
508     pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
509         self.inner.env_remove(key.as_ref());
510         self
511     }
512
513     /// Clears the entire environment map for the child process.
514     ///
515     /// # Examples
516     ///
517     /// Basic usage:
518     ///
519     /// ```no_run
520     /// use std::process::Command;
521     ///
522     /// Command::new("ls")
523     ///         .env_clear()
524     ///         .spawn()
525     ///         .expect("ls command failed to start");
526     /// ```
527     #[stable(feature = "process", since = "1.0.0")]
528     pub fn env_clear(&mut self) -> &mut Command {
529         self.inner.env_clear();
530         self
531     }
532
533     /// Sets the working directory for the child process.
534     ///
535     /// # Examples
536     ///
537     /// Basic usage:
538     ///
539     /// ```no_run
540     /// use std::process::Command;
541     ///
542     /// Command::new("ls")
543     ///         .current_dir("/bin")
544     ///         .spawn()
545     ///         .expect("ls command failed to start");
546     /// ```
547     #[stable(feature = "process", since = "1.0.0")]
548     pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
549         self.inner.cwd(dir.as_ref().as_ref());
550         self
551     }
552
553     /// Configuration for the child process's standard input (stdin) handle.
554     ///
555     /// # Examples
556     ///
557     /// Basic usage:
558     ///
559     /// ```no_run
560     /// use std::process::{Command, Stdio};
561     ///
562     /// Command::new("ls")
563     ///         .stdin(Stdio::null())
564     ///         .spawn()
565     ///         .expect("ls command failed to start");
566     /// ```
567     #[stable(feature = "process", since = "1.0.0")]
568     pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
569         self.inner.stdin(cfg.into().0);
570         self
571     }
572
573     /// Configuration for the child process's standard output (stdout) handle.
574     ///
575     /// # Examples
576     ///
577     /// Basic usage:
578     ///
579     /// ```no_run
580     /// use std::process::{Command, Stdio};
581     ///
582     /// Command::new("ls")
583     ///         .stdout(Stdio::null())
584     ///         .spawn()
585     ///         .expect("ls command failed to start");
586     /// ```
587     #[stable(feature = "process", since = "1.0.0")]
588     pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
589         self.inner.stdout(cfg.into().0);
590         self
591     }
592
593     /// Configuration for the child process's standard error (stderr) handle.
594     ///
595     /// # Examples
596     ///
597     /// Basic usage:
598     ///
599     /// ```no_run
600     /// use std::process::{Command, Stdio};
601     ///
602     /// Command::new("ls")
603     ///         .stderr(Stdio::null())
604     ///         .spawn()
605     ///         .expect("ls command failed to start");
606     /// ```
607     #[stable(feature = "process", since = "1.0.0")]
608     pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
609         self.inner.stderr(cfg.into().0);
610         self
611     }
612
613     /// Executes the command as a child process, returning a handle to it.
614     ///
615     /// By default, stdin, stdout and stderr are inherited from the parent.
616     ///
617     /// # Examples
618     ///
619     /// Basic usage:
620     ///
621     /// ```no_run
622     /// use std::process::Command;
623     ///
624     /// Command::new("ls")
625     ///         .spawn()
626     ///         .expect("ls command failed to start");
627     /// ```
628     #[stable(feature = "process", since = "1.0.0")]
629     pub fn spawn(&mut self) -> io::Result<Child> {
630         self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
631     }
632
633     /// Executes the command as a child process, waiting for it to finish and
634     /// collecting all of its output.
635     ///
636     /// By default, stdin, stdout and stderr are captured (and used to
637     /// provide the resulting output).
638     ///
639     /// # Examples
640     ///
641     /// ```should_panic
642     /// use std::process::Command;
643     /// let output = Command::new("/bin/cat")
644     ///                      .arg("file.txt")
645     ///                      .output()
646     ///                      .expect("failed to execute process");
647     ///
648     /// println!("status: {}", output.status);
649     /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
650     /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
651     ///
652     /// assert!(output.status.success());
653     /// ```
654     #[stable(feature = "process", since = "1.0.0")]
655     pub fn output(&mut self) -> io::Result<Output> {
656         self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
657             .and_then(|p| p.wait_with_output())
658     }
659
660     /// Executes a command as a child process, waiting for it to finish and
661     /// collecting its exit status.
662     ///
663     /// By default, stdin, stdout and stderr are inherited from the parent.
664     ///
665     /// # Examples
666     ///
667     /// ```should_panic
668     /// use std::process::Command;
669     ///
670     /// let status = Command::new("/bin/cat")
671     ///                      .arg("file.txt")
672     ///                      .status()
673     ///                      .expect("failed to execute process");
674     ///
675     /// println!("process exited with: {}", status);
676     ///
677     /// assert!(status.success());
678     /// ```
679     #[stable(feature = "process", since = "1.0.0")]
680     pub fn status(&mut self) -> io::Result<ExitStatus> {
681         self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
682                   .and_then(|mut p| p.wait())
683     }
684 }
685
686 #[stable(feature = "rust1", since = "1.0.0")]
687 impl fmt::Debug for Command {
688     /// Format the program and arguments of a Command for display. Any
689     /// non-utf8 data is lossily converted using the utf8 replacement
690     /// character.
691     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
692         self.inner.fmt(f)
693     }
694 }
695
696 impl AsInner<imp::Command> for Command {
697     fn as_inner(&self) -> &imp::Command { &self.inner }
698 }
699
700 impl AsInnerMut<imp::Command> for Command {
701     fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
702 }
703
704 /// The output of a finished process.
705 ///
706 /// This is returned in a Result by either the [`output`] method of a
707 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
708 /// process.
709 ///
710 /// [`Command`]: struct.Command.html
711 /// [`Child`]: struct.Child.html
712 /// [`output`]: struct.Command.html#method.output
713 /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
714 #[derive(PartialEq, Eq, Clone)]
715 #[stable(feature = "process", since = "1.0.0")]
716 pub struct Output {
717     /// The status (exit code) of the process.
718     #[stable(feature = "process", since = "1.0.0")]
719     pub status: ExitStatus,
720     /// The data that the process wrote to stdout.
721     #[stable(feature = "process", since = "1.0.0")]
722     pub stdout: Vec<u8>,
723     /// The data that the process wrote to stderr.
724     #[stable(feature = "process", since = "1.0.0")]
725     pub stderr: Vec<u8>,
726 }
727
728 // If either stderr or stdout are valid utf8 strings it prints the valid
729 // strings, otherwise it prints the byte sequence instead
730 #[stable(feature = "process_output_debug", since = "1.7.0")]
731 impl fmt::Debug for Output {
732     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
733
734         let stdout_utf8 = str::from_utf8(&self.stdout);
735         let stdout_debug: &fmt::Debug = match stdout_utf8 {
736             Ok(ref str) => str,
737             Err(_) => &self.stdout
738         };
739
740         let stderr_utf8 = str::from_utf8(&self.stderr);
741         let stderr_debug: &fmt::Debug = match stderr_utf8 {
742             Ok(ref str) => str,
743             Err(_) => &self.stderr
744         };
745
746         fmt.debug_struct("Output")
747             .field("status", &self.status)
748             .field("stdout", stdout_debug)
749             .field("stderr", stderr_debug)
750             .finish()
751     }
752 }
753
754 /// Describes what to do with a standard I/O stream for a child process when
755 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
756 ///
757 /// [`stdin`]: struct.Command.html#method.stdin
758 /// [`stdout`]: struct.Command.html#method.stdout
759 /// [`stderr`]: struct.Command.html#method.stderr
760 /// [`Command`]: struct.Command.html
761 #[stable(feature = "process", since = "1.0.0")]
762 pub struct Stdio(imp::Stdio);
763
764 impl Stdio {
765     /// A new pipe should be arranged to connect the parent and child processes.
766     ///
767     /// # Examples
768     ///
769     /// With stdout:
770     ///
771     /// ```no_run
772     /// use std::process::{Command, Stdio};
773     ///
774     /// let output = Command::new("echo")
775     ///     .arg("Hello, world!")
776     ///     .stdout(Stdio::piped())
777     ///     .output()
778     ///     .expect("Failed to execute command");
779     ///
780     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
781     /// // Nothing echoed to console
782     /// ```
783     ///
784     /// With stdin:
785     ///
786     /// ```no_run
787     /// use std::io::Write;
788     /// use std::process::{Command, Stdio};
789     ///
790     /// let mut child = Command::new("rev")
791     ///     .stdin(Stdio::piped())
792     ///     .stdout(Stdio::piped())
793     ///     .spawn()
794     ///     .expect("Failed to spawn child process");
795     ///
796     /// {
797     ///     let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
798     ///     stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
799     /// }
800     ///
801     /// let output = child.wait_with_output().expect("Failed to read stdout");
802     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
803     /// ```
804     #[stable(feature = "process", since = "1.0.0")]
805     pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
806
807     /// The child inherits from the corresponding parent descriptor.
808     ///
809     /// # Examples
810     ///
811     /// With stdout:
812     ///
813     /// ```no_run
814     /// use std::process::{Command, Stdio};
815     ///
816     /// let output = Command::new("echo")
817     ///     .arg("Hello, world!")
818     ///     .stdout(Stdio::inherit())
819     ///     .output()
820     ///     .expect("Failed to execute command");
821     ///
822     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
823     /// // "Hello, world!" echoed to console
824     /// ```
825     ///
826     /// With stdin:
827     ///
828     /// ```no_run
829     /// use std::process::{Command, Stdio};
830     ///
831     /// let output = Command::new("rev")
832     ///     .stdin(Stdio::inherit())
833     ///     .stdout(Stdio::piped())
834     ///     .output()
835     ///     .expect("Failed to execute command");
836     ///
837     /// println!("You piped in the reverse of: {}", String::from_utf8_lossy(&output.stdout));
838     /// ```
839     #[stable(feature = "process", since = "1.0.0")]
840     pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
841
842     /// This stream will be ignored. This is the equivalent of attaching the
843     /// stream to `/dev/null`
844     ///
845     /// # Examples
846     ///
847     /// With stdout:
848     ///
849     /// ```no_run
850     /// use std::process::{Command, Stdio};
851     ///
852     /// let output = Command::new("echo")
853     ///     .arg("Hello, world!")
854     ///     .stdout(Stdio::null())
855     ///     .output()
856     ///     .expect("Failed to execute command");
857     ///
858     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
859     /// // Nothing echoed to console
860     /// ```
861     ///
862     /// With stdin:
863     ///
864     /// ```no_run
865     /// use std::process::{Command, Stdio};
866     ///
867     /// let output = Command::new("rev")
868     ///     .stdin(Stdio::null())
869     ///     .stdout(Stdio::piped())
870     ///     .output()
871     ///     .expect("Failed to execute command");
872     ///
873     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
874     /// // Ignores any piped-in input
875     /// ```
876     #[stable(feature = "process", since = "1.0.0")]
877     pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
878 }
879
880 impl FromInner<imp::Stdio> for Stdio {
881     fn from_inner(inner: imp::Stdio) -> Stdio {
882         Stdio(inner)
883     }
884 }
885
886 #[stable(feature = "std_debug", since = "1.16.0")]
887 impl fmt::Debug for Stdio {
888     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
889         f.pad("Stdio { .. }")
890     }
891 }
892
893 #[stable(feature = "stdio_from", since = "1.20.0")]
894 impl From<ChildStdin> for Stdio {
895     fn from(child: ChildStdin) -> Stdio {
896         Stdio::from_inner(child.into_inner().into())
897     }
898 }
899
900 #[stable(feature = "stdio_from", since = "1.20.0")]
901 impl From<ChildStdout> for Stdio {
902     fn from(child: ChildStdout) -> Stdio {
903         Stdio::from_inner(child.into_inner().into())
904     }
905 }
906
907 #[stable(feature = "stdio_from", since = "1.20.0")]
908 impl From<ChildStderr> for Stdio {
909     fn from(child: ChildStderr) -> Stdio {
910         Stdio::from_inner(child.into_inner().into())
911     }
912 }
913
914 #[stable(feature = "stdio_from", since = "1.20.0")]
915 impl From<fs::File> for Stdio {
916     fn from(file: fs::File) -> Stdio {
917         Stdio::from_inner(file.into_inner().into())
918     }
919 }
920
921 /// Describes the result of a process after it has terminated.
922 ///
923 /// This `struct` is used to represent the exit status of a child process.
924 /// Child processes are created via the [`Command`] struct and their exit
925 /// status is exposed through the [`status`] method.
926 ///
927 /// [`Command`]: struct.Command.html
928 /// [`status`]: struct.Command.html#method.status
929 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
930 #[stable(feature = "process", since = "1.0.0")]
931 pub struct ExitStatus(imp::ExitStatus);
932
933 impl ExitStatus {
934     /// Was termination successful? Signal termination is not considered a
935     /// success, and success is defined as a zero exit status.
936     ///
937     /// # Examples
938     ///
939     /// ```rust,no_run
940     /// use std::process::Command;
941     ///
942     /// let status = Command::new("mkdir")
943     ///                      .arg("projects")
944     ///                      .status()
945     ///                      .expect("failed to execute mkdir");
946     ///
947     /// if status.success() {
948     ///     println!("'projects/' directory created");
949     /// } else {
950     ///     println!("failed to create 'projects/' directory");
951     /// }
952     /// ```
953     #[stable(feature = "process", since = "1.0.0")]
954     pub fn success(&self) -> bool {
955         self.0.success()
956     }
957
958     /// Returns the exit code of the process, if any.
959     ///
960     /// On Unix, this will return `None` if the process was terminated
961     /// by a signal; `std::os::unix` provides an extension trait for
962     /// extracting the signal and other details from the `ExitStatus`.
963     ///
964     /// # Examples
965     ///
966     /// ```no_run
967     /// use std::process::Command;
968     ///
969     /// let status = Command::new("mkdir")
970     ///                      .arg("projects")
971     ///                      .status()
972     ///                      .expect("failed to execute mkdir");
973     ///
974     /// match status.code() {
975     ///     Some(code) => println!("Exited with status code: {}", code),
976     ///     None       => println!("Process terminated by signal")
977     /// }
978     /// ```
979     #[stable(feature = "process", since = "1.0.0")]
980     pub fn code(&self) -> Option<i32> {
981         self.0.code()
982     }
983 }
984
985 impl AsInner<imp::ExitStatus> for ExitStatus {
986     fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
987 }
988
989 impl FromInner<imp::ExitStatus> for ExitStatus {
990     fn from_inner(s: imp::ExitStatus) -> ExitStatus {
991         ExitStatus(s)
992     }
993 }
994
995 #[stable(feature = "process", since = "1.0.0")]
996 impl fmt::Display for ExitStatus {
997     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
998         self.0.fmt(f)
999     }
1000 }
1001
1002 impl Child {
1003     /// Forces the child to exit. This is equivalent to sending a
1004     /// SIGKILL on unix platforms.
1005     ///
1006     /// # Examples
1007     ///
1008     /// Basic usage:
1009     ///
1010     /// ```no_run
1011     /// use std::process::Command;
1012     ///
1013     /// let mut command = Command::new("yes");
1014     /// if let Ok(mut child) = command.spawn() {
1015     ///     child.kill().expect("command wasn't running");
1016     /// } else {
1017     ///     println!("yes command didn't start");
1018     /// }
1019     /// ```
1020     #[stable(feature = "process", since = "1.0.0")]
1021     pub fn kill(&mut self) -> io::Result<()> {
1022         self.handle.kill()
1023     }
1024
1025     /// Returns the OS-assigned process identifier associated with this child.
1026     ///
1027     /// # Examples
1028     ///
1029     /// Basic usage:
1030     ///
1031     /// ```no_run
1032     /// use std::process::Command;
1033     ///
1034     /// let mut command = Command::new("ls");
1035     /// if let Ok(child) = command.spawn() {
1036     ///     println!("Child's id is {}", child.id());
1037     /// } else {
1038     ///     println!("ls command didn't start");
1039     /// }
1040     /// ```
1041     #[stable(feature = "process_id", since = "1.3.0")]
1042     pub fn id(&self) -> u32 {
1043         self.handle.id()
1044     }
1045
1046     /// Waits for the child to exit completely, returning the status that it
1047     /// exited with. This function will continue to have the same return value
1048     /// after it has been called at least once.
1049     ///
1050     /// The stdin handle to the child process, if any, will be closed
1051     /// before waiting. This helps avoid deadlock: it ensures that the
1052     /// child does not block waiting for input from the parent, while
1053     /// the parent waits for the child to exit.
1054     ///
1055     /// # Examples
1056     ///
1057     /// Basic usage:
1058     ///
1059     /// ```no_run
1060     /// use std::process::Command;
1061     ///
1062     /// let mut command = Command::new("ls");
1063     /// if let Ok(mut child) = command.spawn() {
1064     ///     child.wait().expect("command wasn't running");
1065     ///     println!("Child has finished its execution!");
1066     /// } else {
1067     ///     println!("ls command didn't start");
1068     /// }
1069     /// ```
1070     #[stable(feature = "process", since = "1.0.0")]
1071     pub fn wait(&mut self) -> io::Result<ExitStatus> {
1072         drop(self.stdin.take());
1073         self.handle.wait().map(ExitStatus)
1074     }
1075
1076     /// Attempts to collect the exit status of the child if it has already
1077     /// exited.
1078     ///
1079     /// This function will not block the calling thread and will only advisorily
1080     /// check to see if the child process has exited or not. If the child has
1081     /// exited then on Unix the process id is reaped. This function is
1082     /// guaranteed to repeatedly return a successful exit status so long as the
1083     /// child has already exited.
1084     ///
1085     /// If the child has exited, then `Ok(Some(status))` is returned. If the
1086     /// exit status is not available at this time then `Ok(None)` is returned.
1087     /// If an error occurs, then that error is returned.
1088     ///
1089     /// Note that unlike `wait`, this function will not attempt to drop stdin.
1090     ///
1091     /// # Examples
1092     ///
1093     /// Basic usage:
1094     ///
1095     /// ```no_run
1096     /// use std::process::Command;
1097     ///
1098     /// let mut child = Command::new("ls").spawn().unwrap();
1099     ///
1100     /// match child.try_wait() {
1101     ///     Ok(Some(status)) => println!("exited with: {}", status),
1102     ///     Ok(None) => {
1103     ///         println!("status not ready yet, let's really wait");
1104     ///         let res = child.wait();
1105     ///         println!("result: {:?}", res);
1106     ///     }
1107     ///     Err(e) => println!("error attempting to wait: {}", e),
1108     /// }
1109     /// ```
1110     #[stable(feature = "process_try_wait", since = "1.18.0")]
1111     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1112         Ok(self.handle.try_wait()?.map(ExitStatus))
1113     }
1114
1115     /// Simultaneously waits for the child to exit and collect all remaining
1116     /// output on the stdout/stderr handles, returning an `Output`
1117     /// instance.
1118     ///
1119     /// The stdin handle to the child process, if any, will be closed
1120     /// before waiting. This helps avoid deadlock: it ensures that the
1121     /// child does not block waiting for input from the parent, while
1122     /// the parent waits for the child to exit.
1123     ///
1124     /// By default, stdin, stdout and stderr are inherited from the parent.
1125     /// In order to capture the output into this `Result<Output>` it is
1126     /// necessary to create new pipes between parent and child. Use
1127     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1128     ///
1129     /// # Examples
1130     ///
1131     /// ```should_panic
1132     /// use std::process::{Command, Stdio};
1133     ///
1134     /// let child = Command::new("/bin/cat")
1135     ///     .arg("file.txt")
1136     ///     .stdout(Stdio::piped())
1137     ///     .spawn()
1138     ///     .expect("failed to execute child");
1139     ///
1140     /// let output = child
1141     ///     .wait_with_output()
1142     ///     .expect("failed to wait on child");
1143     ///
1144     /// assert!(output.status.success());
1145     /// ```
1146     ///
1147     #[stable(feature = "process", since = "1.0.0")]
1148     pub fn wait_with_output(mut self) -> io::Result<Output> {
1149         drop(self.stdin.take());
1150
1151         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1152         match (self.stdout.take(), self.stderr.take()) {
1153             (None, None) => {}
1154             (Some(mut out), None) => {
1155                 let res = out.read_to_end(&mut stdout);
1156                 res.unwrap();
1157             }
1158             (None, Some(mut err)) => {
1159                 let res = err.read_to_end(&mut stderr);
1160                 res.unwrap();
1161             }
1162             (Some(out), Some(err)) => {
1163                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1164                 res.unwrap();
1165             }
1166         }
1167
1168         let status = self.wait()?;
1169         Ok(Output {
1170             status,
1171             stdout,
1172             stderr,
1173         })
1174     }
1175 }
1176
1177 /// Terminates the current process with the specified exit code.
1178 ///
1179 /// This function will never return and will immediately terminate the current
1180 /// process. The exit code is passed through to the underlying OS and will be
1181 /// available for consumption by another process.
1182 ///
1183 /// Note that because this function never returns, and that it terminates the
1184 /// process, no destructors on the current stack or any other thread's stack
1185 /// will be run. If a clean shutdown is needed it is recommended to only call
1186 /// this function at a known point where there are no more destructors left
1187 /// to run.
1188 ///
1189 /// ## Platform-specific behavior
1190 ///
1191 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1192 /// will be visible to a parent process inspecting the exit code. On most
1193 /// Unix-like platforms, only the eight least-significant bits are considered.
1194 ///
1195 /// # Examples
1196 ///
1197 /// Due to this function’s behavior regarding destructors, a conventional way
1198 /// to use the function is to extract the actual computation to another
1199 /// function and compute the exit code from its return value:
1200 ///
1201 /// ```
1202 /// fn run_app() -> Result<(), ()> {
1203 ///     // Application logic here
1204 ///     Ok(())
1205 /// }
1206 ///
1207 /// fn main() {
1208 ///     ::std::process::exit(match run_app() {
1209 ///        Ok(_) => 0,
1210 ///        Err(err) => {
1211 ///            eprintln!("error: {:?}", err);
1212 ///            1
1213 ///        }
1214 ///     });
1215 /// }
1216 /// ```
1217 ///
1218 /// Due to [platform-specific behavior], the exit code for this example will be
1219 /// `0` on Linux, but `256` on Windows:
1220 ///
1221 /// ```no_run
1222 /// use std::process;
1223 ///
1224 /// process::exit(0x0100);
1225 /// ```
1226 ///
1227 /// [platform-specific behavior]: #platform-specific-behavior
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub fn exit(code: i32) -> ! {
1230     ::sys_common::cleanup();
1231     ::sys::os::exit(code)
1232 }
1233
1234 /// Terminates the process in an abnormal fashion.
1235 ///
1236 /// The function will never return and will immediately terminate the current
1237 /// process in a platform specific "abnormal" manner.
1238 ///
1239 /// Note that because this function never returns, and that it terminates the
1240 /// process, no destructors on the current stack or any other thread's stack
1241 /// will be run.
1242 ///
1243 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1244 /// the current thread's stack and calls all destructors.
1245 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1246 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1247 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1248 ///
1249 /// If a clean shutdown is needed it is recommended to only call
1250 /// this function at a known point where there are no more destructors left
1251 /// to run.
1252 ///
1253 /// # Examples
1254 ///
1255 /// ```no_run
1256 /// use std::process;
1257 ///
1258 /// fn main() {
1259 ///     println!("aborting");
1260 ///
1261 ///     process::abort();
1262 ///
1263 ///     // execution never gets here
1264 /// }
1265 /// ```
1266 ///
1267 /// The `abort` function terminates the process, so the destructor will not
1268 /// get run on the example below:
1269 ///
1270 /// ```no_run
1271 /// use std::process;
1272 ///
1273 /// struct HasDrop;
1274 ///
1275 /// impl Drop for HasDrop {
1276 ///     fn drop(&mut self) {
1277 ///         println!("This will never be printed!");
1278 ///     }
1279 /// }
1280 ///
1281 /// fn main() {
1282 ///     let _x = HasDrop;
1283 ///     process::abort();
1284 ///     // the destructor implemented for HasDrop will never get run
1285 /// }
1286 /// ```
1287 ///
1288 /// [`panic!`]: ../../std/macro.panic.html
1289 /// [panic hook]: ../../std/panic/fn.set_hook.html
1290 #[stable(feature = "process_abort", since = "1.17.0")]
1291 pub fn abort() -> ! {
1292     unsafe { ::sys::abort_internal() };
1293 }
1294
1295 #[cfg(all(test, not(target_os = "emscripten")))]
1296 mod tests {
1297     use io::prelude::*;
1298
1299     use io::ErrorKind;
1300     use str;
1301     use super::{Command, Output, Stdio};
1302
1303     // FIXME(#10380) these tests should not all be ignored on android.
1304
1305     #[test]
1306     #[cfg_attr(target_os = "android", ignore)]
1307     fn smoke() {
1308         let p = if cfg!(target_os = "windows") {
1309             Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1310         } else {
1311             Command::new("true").spawn()
1312         };
1313         assert!(p.is_ok());
1314         let mut p = p.unwrap();
1315         assert!(p.wait().unwrap().success());
1316     }
1317
1318     #[test]
1319     #[cfg_attr(target_os = "android", ignore)]
1320     fn smoke_failure() {
1321         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1322             Ok(..) => panic!(),
1323             Err(..) => {}
1324         }
1325     }
1326
1327     #[test]
1328     #[cfg_attr(target_os = "android", ignore)]
1329     fn exit_reported_right() {
1330         let p = if cfg!(target_os = "windows") {
1331             Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1332         } else {
1333             Command::new("false").spawn()
1334         };
1335         assert!(p.is_ok());
1336         let mut p = p.unwrap();
1337         assert!(p.wait().unwrap().code() == Some(1));
1338         drop(p.wait());
1339     }
1340
1341     #[test]
1342     #[cfg(unix)]
1343     #[cfg_attr(target_os = "android", ignore)]
1344     fn signal_reported_right() {
1345         use os::unix::process::ExitStatusExt;
1346
1347         let mut p = Command::new("/bin/sh")
1348                             .arg("-c").arg("read a")
1349                             .stdin(Stdio::piped())
1350                             .spawn().unwrap();
1351         p.kill().unwrap();
1352         match p.wait().unwrap().signal() {
1353             Some(9) => {},
1354             result => panic!("not terminated by signal 9 (instead, {:?})",
1355                              result),
1356         }
1357     }
1358
1359     pub fn run_output(mut cmd: Command) -> String {
1360         let p = cmd.spawn();
1361         assert!(p.is_ok());
1362         let mut p = p.unwrap();
1363         assert!(p.stdout.is_some());
1364         let mut ret = String::new();
1365         p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1366         assert!(p.wait().unwrap().success());
1367         return ret;
1368     }
1369
1370     #[test]
1371     #[cfg_attr(target_os = "android", ignore)]
1372     fn stdout_works() {
1373         if cfg!(target_os = "windows") {
1374             let mut cmd = Command::new("cmd");
1375             cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1376             assert_eq!(run_output(cmd), "foobar\r\n");
1377         } else {
1378             let mut cmd = Command::new("echo");
1379             cmd.arg("foobar").stdout(Stdio::piped());
1380             assert_eq!(run_output(cmd), "foobar\n");
1381         }
1382     }
1383
1384     #[test]
1385     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1386     fn set_current_dir_works() {
1387         let mut cmd = Command::new("/bin/sh");
1388         cmd.arg("-c").arg("pwd")
1389            .current_dir("/")
1390            .stdout(Stdio::piped());
1391         assert_eq!(run_output(cmd), "/\n");
1392     }
1393
1394     #[test]
1395     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1396     fn stdin_works() {
1397         let mut p = Command::new("/bin/sh")
1398                             .arg("-c").arg("read line; echo $line")
1399                             .stdin(Stdio::piped())
1400                             .stdout(Stdio::piped())
1401                             .spawn().unwrap();
1402         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1403         drop(p.stdin.take());
1404         let mut out = String::new();
1405         p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1406         assert!(p.wait().unwrap().success());
1407         assert_eq!(out, "foobar\n");
1408     }
1409
1410
1411     #[test]
1412     #[cfg_attr(target_os = "android", ignore)]
1413     #[cfg(unix)]
1414     fn uid_works() {
1415         use os::unix::prelude::*;
1416         use libc;
1417         let mut p = Command::new("/bin/sh")
1418                             .arg("-c").arg("true")
1419                             .uid(unsafe { libc::getuid() })
1420                             .gid(unsafe { libc::getgid() })
1421                             .spawn().unwrap();
1422         assert!(p.wait().unwrap().success());
1423     }
1424
1425     #[test]
1426     #[cfg_attr(target_os = "android", ignore)]
1427     #[cfg(unix)]
1428     fn uid_to_root_fails() {
1429         use os::unix::prelude::*;
1430         use libc;
1431
1432         // if we're already root, this isn't a valid test. Most of the bots run
1433         // as non-root though (android is an exception).
1434         if unsafe { libc::getuid() == 0 } { return }
1435         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1436     }
1437
1438     #[test]
1439     #[cfg_attr(target_os = "android", ignore)]
1440     fn test_process_status() {
1441         let mut status = if cfg!(target_os = "windows") {
1442             Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1443         } else {
1444             Command::new("false").status().unwrap()
1445         };
1446         assert!(status.code() == Some(1));
1447
1448         status = if cfg!(target_os = "windows") {
1449             Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1450         } else {
1451             Command::new("true").status().unwrap()
1452         };
1453         assert!(status.success());
1454     }
1455
1456     #[test]
1457     fn test_process_output_fail_to_start() {
1458         match Command::new("/no-binary-by-this-name-should-exist").output() {
1459             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1460             Ok(..) => panic!()
1461         }
1462     }
1463
1464     #[test]
1465     #[cfg_attr(target_os = "android", ignore)]
1466     fn test_process_output_output() {
1467         let Output {status, stdout, stderr}
1468              = if cfg!(target_os = "windows") {
1469                  Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1470              } else {
1471                  Command::new("echo").arg("hello").output().unwrap()
1472              };
1473         let output_str = str::from_utf8(&stdout).unwrap();
1474
1475         assert!(status.success());
1476         assert_eq!(output_str.trim().to_string(), "hello");
1477         assert_eq!(stderr, Vec::new());
1478     }
1479
1480     #[test]
1481     #[cfg_attr(target_os = "android", ignore)]
1482     fn test_process_output_error() {
1483         let Output {status, stdout, stderr}
1484              = if cfg!(target_os = "windows") {
1485                  Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1486              } else {
1487                  Command::new("mkdir").arg(".").output().unwrap()
1488              };
1489
1490         assert!(status.code() == Some(1));
1491         assert_eq!(stdout, Vec::new());
1492         assert!(!stderr.is_empty());
1493     }
1494
1495     #[test]
1496     #[cfg_attr(target_os = "android", ignore)]
1497     fn test_finish_once() {
1498         let mut prog = if cfg!(target_os = "windows") {
1499             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1500         } else {
1501             Command::new("false").spawn().unwrap()
1502         };
1503         assert!(prog.wait().unwrap().code() == Some(1));
1504     }
1505
1506     #[test]
1507     #[cfg_attr(target_os = "android", ignore)]
1508     fn test_finish_twice() {
1509         let mut prog = if cfg!(target_os = "windows") {
1510             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1511         } else {
1512             Command::new("false").spawn().unwrap()
1513         };
1514         assert!(prog.wait().unwrap().code() == Some(1));
1515         assert!(prog.wait().unwrap().code() == Some(1));
1516     }
1517
1518     #[test]
1519     #[cfg_attr(target_os = "android", ignore)]
1520     fn test_wait_with_output_once() {
1521         let prog = if cfg!(target_os = "windows") {
1522             Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1523         } else {
1524             Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1525         };
1526
1527         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1528         let output_str = str::from_utf8(&stdout).unwrap();
1529
1530         assert!(status.success());
1531         assert_eq!(output_str.trim().to_string(), "hello");
1532         assert_eq!(stderr, Vec::new());
1533     }
1534
1535     #[cfg(all(unix, not(target_os="android")))]
1536     pub fn env_cmd() -> Command {
1537         Command::new("env")
1538     }
1539     #[cfg(target_os="android")]
1540     pub fn env_cmd() -> Command {
1541         let mut cmd = Command::new("/system/bin/sh");
1542         cmd.arg("-c").arg("set");
1543         cmd
1544     }
1545
1546     #[cfg(windows)]
1547     pub fn env_cmd() -> Command {
1548         let mut cmd = Command::new("cmd");
1549         cmd.arg("/c").arg("set");
1550         cmd
1551     }
1552
1553     #[test]
1554     fn test_inherit_env() {
1555         use env;
1556
1557         let result = env_cmd().output().unwrap();
1558         let output = String::from_utf8(result.stdout).unwrap();
1559
1560         for (ref k, ref v) in env::vars() {
1561             // Don't check android RANDOM variable which seems to change
1562             // whenever the shell runs, and our `env_cmd` is indeed running a
1563             // shell which means it'll get a different RANDOM than we probably
1564             // have.
1565             //
1566             // Also skip env vars with `-` in the name on android because, well,
1567             // I'm not sure. It appears though that the `set` command above does
1568             // not print env vars with `-` in the name, so we just skip them
1569             // here as we won't find them in the output. Note that most env vars
1570             // use `_` instead of `-`, but our build system sets a few env vars
1571             // with `-` in the name.
1572             if cfg!(target_os = "android") &&
1573                (*k == "RANDOM" || k.contains("-")) {
1574                 continue
1575             }
1576
1577             // Windows has hidden environment variables whose names start with
1578             // equals signs (`=`). Those do not show up in the output of the
1579             // `set` command.
1580             assert!((cfg!(windows) && k.starts_with("=")) ||
1581                     k.starts_with("DYLD") ||
1582                     output.contains(&format!("{}={}", *k, *v)) ||
1583                     output.contains(&format!("{}='{}'", *k, *v)),
1584                     "output doesn't contain `{}={}`\n{}",
1585                     k, v, output);
1586         }
1587     }
1588
1589     #[test]
1590     fn test_override_env() {
1591         use env;
1592
1593         // In some build environments (such as chrooted Nix builds), `env` can
1594         // only be found in the explicitly-provided PATH env variable, not in
1595         // default places such as /bin or /usr/bin. So we need to pass through
1596         // PATH to our sub-process.
1597         let mut cmd = env_cmd();
1598         cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1599         if let Some(p) = env::var_os("PATH") {
1600             cmd.env("PATH", &p);
1601         }
1602         let result = cmd.output().unwrap();
1603         let output = String::from_utf8_lossy(&result.stdout).to_string();
1604
1605         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1606                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1607     }
1608
1609     #[test]
1610     fn test_add_to_env() {
1611         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1612         let output = String::from_utf8_lossy(&result.stdout).to_string();
1613
1614         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1615                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1616     }
1617
1618     // Regression tests for #30858.
1619     #[test]
1620     fn test_interior_nul_in_progname_is_error() {
1621         match Command::new("has-some-\0\0s-inside").spawn() {
1622             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1623             Ok(_) => panic!(),
1624         }
1625     }
1626
1627     #[test]
1628     fn test_interior_nul_in_arg_is_error() {
1629         match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1630             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1631             Ok(_) => panic!(),
1632         }
1633     }
1634
1635     #[test]
1636     fn test_interior_nul_in_args_is_error() {
1637         match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1638             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1639             Ok(_) => panic!(),
1640         }
1641     }
1642
1643     #[test]
1644     fn test_interior_nul_in_current_dir_is_error() {
1645         match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1646             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1647             Ok(_) => panic!(),
1648         }
1649     }
1650
1651     // Regression tests for #30862.
1652     #[test]
1653     fn test_interior_nul_in_env_key_is_error() {
1654         match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1655             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1656             Ok(_) => panic!(),
1657         }
1658     }
1659
1660     #[test]
1661     fn test_interior_nul_in_env_value_is_error() {
1662         match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1663             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1664             Ok(_) => panic!(),
1665         }
1666     }
1667
1668     /// Test that process creation flags work by debugging a process.
1669     /// Other creation flags make it hard or impossible to detect
1670     /// behavioral changes in the process.
1671     #[test]
1672     #[cfg(windows)]
1673     fn test_creation_flags() {
1674         use os::windows::process::CommandExt;
1675         use sys::c::{BOOL, DWORD, INFINITE};
1676         #[repr(C, packed)]
1677         struct DEBUG_EVENT {
1678             pub event_code: DWORD,
1679             pub process_id: DWORD,
1680             pub thread_id: DWORD,
1681             // This is a union in the real struct, but we don't
1682             // need this data for the purposes of this test.
1683             pub _junk: [u8; 164],
1684         }
1685
1686         extern "system" {
1687             fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1688             fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1689                                   dwContinueStatus: DWORD) -> BOOL;
1690         }
1691
1692         const DEBUG_PROCESS: DWORD = 1;
1693         const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1694         const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1695
1696         let mut child = Command::new("cmd")
1697             .creation_flags(DEBUG_PROCESS)
1698             .stdin(Stdio::piped()).spawn().unwrap();
1699         child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1700         let mut events = 0;
1701         let mut event = DEBUG_EVENT {
1702             event_code: 0,
1703             process_id: 0,
1704             thread_id: 0,
1705             _junk: [0; 164],
1706         };
1707         loop {
1708             if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1709                 panic!("WaitForDebugEvent failed!");
1710             }
1711             events += 1;
1712
1713             if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1714                 break;
1715             }
1716
1717             if unsafe { ContinueDebugEvent(event.process_id,
1718                                            event.thread_id,
1719                                            DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1720                 panic!("ContinueDebugEvent failed!");
1721             }
1722         }
1723         assert!(events > 0);
1724     }
1725 }