]> git.lizzy.rs Git - rust.git/blob - src/libstd/process.rs
5a06bf45aaabdff434e7f677235dbb69d33eee0a
[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 //! This module is mostly concerned with spawning and interacting with child
14 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
15 //! current process.
16 //!
17 //! # Spawning a process
18 //!
19 //! The [`Command`] struct is used to configure and spawn processes:
20 //!
21 //! ```
22 //! use std::process::Command;
23 //!
24 //! let output = Command::new("echo")
25 //!                      .arg("Hello world")
26 //!                      .output()
27 //!                      .expect("Failed to execute command");
28 //!
29 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
30 //! ```
31 //!
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.
36 //!
37 //! # Handling I/O
38 //!
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
43 //! like so:
44 //!
45 //! ```no_run
46 //! use std::process::{Command, Stdio};
47 //!
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())
53 //!     .spawn()
54 //!     .expect("Failed to start echo process");
55 //!
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");
59 //!
60 //! let mut sed_child = Command::new("sed")
61 //!     .arg("s/tpyo/typo/")
62 //!     .stdin(Stdio::from(echo_out))
63 //!     .stdout(Stdio::piped())
64 //!     .spawn()
65 //!     .expect("Failed to start sed process");
66 //!
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());
69 //! ```
70 //!
71 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
72 //! [`ChildStdin`] implements [`Write`]:
73 //!
74 //! ```no_run
75 //! use std::process::{Command, Stdio};
76 //! use std::io::Write;
77 //!
78 //! let mut child = Command::new("/bin/cat")
79 //!     .stdin(Stdio::piped())
80 //!     .stdout(Stdio::piped())
81 //!     .spawn()
82 //!     .expect("failed to execute child");
83 //!
84 //! {
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");
88 //! }
89 //!
90 //! let output = child
91 //!     .wait_with_output()
92 //!     .expect("failed to wait on child");
93 //!
94 //! assert_eq!(b"test", output.stdout.as_slice());
95 //! ```
96 //!
97 //! [`abort`]: fn.abort.html
98 //! [`exit`]: fn.exit.html
99 //!
100 //! [`Command`]: struct.Command.html
101 //! [`spawn`]: struct.Command.html#method.spawn
102 //! [`output`]: struct.Command.html#method.output
103 //!
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
109 //!
110 //! [`stdout`]: struct.Command.html#method.stdout
111 //! [`stdin`]: struct.Command.html#method.stdin
112 //! [`stderr`]: struct.Command.html#method.stderr
113 //!
114 //! [`Write`]: ../io/trait.Write.html
115 //! [`Read`]: ../io/trait.Read.html
116
117 #![stable(feature = "process", since = "1.0.0")]
118
119 use io::prelude::*;
120
121 use ffi::OsStr;
122 use fmt;
123 use fs;
124 use io::{self, Initializer};
125 use path::Path;
126 use str;
127 use sys::pipe::{read2, AnonPipe};
128 use sys::process as imp;
129 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
130
131 /// Representation of a running or exited child process.
132 ///
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
136 /// interface.
137 ///
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
141 /// scope.
142 ///
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
145 /// continuing.
146 ///
147 /// # Examples
148 ///
149 /// ```should_panic
150 /// use std::process::Command;
151 ///
152 /// let mut child = Command::new("/bin/cat")
153 ///                         .arg("file.txt")
154 ///                         .spawn()
155 ///                         .expect("failed to execute child");
156 ///
157 /// let ecode = child.wait()
158 ///                  .expect("failed to wait on child");
159 ///
160 /// assert!(ecode.success());
161 /// ```
162 ///
163 /// [`Command`]: struct.Command.html
164 /// [`Drop`]: ../../core/ops/trait.Drop.html
165 /// [`wait`]: #method.wait
166 #[stable(feature = "process", since = "1.0.0")]
167 pub struct Child {
168     handle: imp::Process,
169
170     /// The handle for writing to the child's standard input (stdin), if it has
171     /// been captured.
172     #[stable(feature = "process", since = "1.0.0")]
173     pub stdin: Option<ChildStdin>,
174
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>,
179
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>,
184 }
185
186 impl AsInner<imp::Process> for Child {
187     fn as_inner(&self) -> &imp::Process { &self.handle }
188 }
189
190 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
191     fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
192         Child {
193             handle,
194             stdin: io.stdin.map(ChildStdin::from_inner),
195             stdout: io.stdout.map(ChildStdout::from_inner),
196             stderr: io.stderr.map(ChildStderr::from_inner),
197         }
198     }
199 }
200
201 impl IntoInner<imp::Process> for Child {
202     fn into_inner(self) -> imp::Process { self.handle }
203 }
204
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)
212             .finish()
213     }
214 }
215
216 /// A handle to a child process's standard input (stdin).
217 ///
218 /// This struct is used in the [`stdin`] field on [`Child`].
219 ///
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.
223 ///
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 {
229     inner: AnonPipe
230 }
231
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)
236     }
237
238     fn flush(&mut self) -> io::Result<()> {
239         Ok(())
240     }
241 }
242
243 impl AsInner<AnonPipe> for ChildStdin {
244     fn as_inner(&self) -> &AnonPipe { &self.inner }
245 }
246
247 impl IntoInner<AnonPipe> for ChildStdin {
248     fn into_inner(self) -> AnonPipe { self.inner }
249 }
250
251 impl FromInner<AnonPipe> for ChildStdin {
252     fn from_inner(pipe: AnonPipe) -> ChildStdin {
253         ChildStdin { inner: pipe }
254     }
255 }
256
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 { .. }")
261     }
262 }
263
264 /// A handle to a child process's standard output (stdout).
265 ///
266 /// This struct is used in the [`stdout`] field on [`Child`].
267 ///
268 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
269 /// underlying file handle will be closed.
270 ///
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 {
276     inner: AnonPipe
277 }
278
279 #[stable(feature = "process", since = "1.0.0")]
280 impl Read for ChildStdout {
281     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
282         self.inner.read(buf)
283     }
284     #[inline]
285     unsafe fn initializer(&self) -> Initializer {
286         Initializer::nop()
287     }
288 }
289
290 impl AsInner<AnonPipe> for ChildStdout {
291     fn as_inner(&self) -> &AnonPipe { &self.inner }
292 }
293
294 impl IntoInner<AnonPipe> for ChildStdout {
295     fn into_inner(self) -> AnonPipe { self.inner }
296 }
297
298 impl FromInner<AnonPipe> for ChildStdout {
299     fn from_inner(pipe: AnonPipe) -> ChildStdout {
300         ChildStdout { inner: pipe }
301     }
302 }
303
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 { .. }")
308     }
309 }
310
311 /// A handle to a child process's stderr.
312 ///
313 /// This struct is used in the [`stderr`] field on [`Child`].
314 ///
315 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
316 /// underlying file handle will be closed.
317 ///
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 {
323     inner: AnonPipe
324 }
325
326 #[stable(feature = "process", since = "1.0.0")]
327 impl Read for ChildStderr {
328     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
329         self.inner.read(buf)
330     }
331     #[inline]
332     unsafe fn initializer(&self) -> Initializer {
333         Initializer::nop()
334     }
335 }
336
337 impl AsInner<AnonPipe> for ChildStderr {
338     fn as_inner(&self) -> &AnonPipe { &self.inner }
339 }
340
341 impl IntoInner<AnonPipe> for ChildStderr {
342     fn into_inner(self) -> AnonPipe { self.inner }
343 }
344
345 impl FromInner<AnonPipe> for ChildStderr {
346     fn from_inner(pipe: AnonPipe) -> ChildStderr {
347         ChildStderr { inner: pipe }
348     }
349 }
350
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 { .. }")
355     }
356 }
357
358 /// A process builder, providing fine-grained control
359 /// over how a new process should be spawned.
360 ///
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:
365 ///
366 /// ```
367 /// use std::process::Command;
368 ///
369 /// let output = if cfg!(target_os = "windows") {
370 ///     Command::new("cmd")
371 ///             .args(&["/C", "echo hello"])
372 ///             .output()
373 ///             .expect("failed to execute process")
374 /// } else {
375 ///     Command::new("sh")
376 ///             .arg("-c")
377 ///             .arg("echo hello")
378 ///             .output()
379 ///             .expect("failed to execute process")
380 /// };
381 ///
382 /// let hello = output.stdout;
383 /// ```
384 #[stable(feature = "process", since = "1.0.0")]
385 pub struct Command {
386     inner: imp::Command,
387 }
388
389 impl Command {
390     /// Constructs a new `Command` for launching the program at
391     /// path `program`, with the following default configuration:
392     ///
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`
397     ///
398     /// Builder methods are provided to change these defaults and
399     /// otherwise configure the process.
400     ///
401     /// If `program` is not an absolute path, the `PATH` will be searched in
402     /// an OS-defined way.
403     ///
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>).
408     ///
409     /// # Examples
410     ///
411     /// Basic usage:
412     ///
413     /// ```no_run
414     /// use std::process::Command;
415     ///
416     /// Command::new("sh")
417     ///         .spawn()
418     ///         .expect("sh command failed to start");
419     /// ```
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()) }
423     }
424
425     /// Add an argument to pass to the program.
426     ///
427     /// Only one argument can be passed per use. So instead of:
428     ///
429     /// ```no_run
430     /// # std::process::Command::new("sh")
431     /// .arg("-C /path/to/repo")
432     /// # ;
433     /// ```
434     ///
435     /// usage would be:
436     ///
437     /// ```no_run
438     /// # std::process::Command::new("sh")
439     /// .arg("-C")
440     /// .arg("/path/to/repo")
441     /// # ;
442     /// ```
443     ///
444     /// To pass multiple arguments see [`args`].
445     ///
446     /// [`args`]: #method.args
447     ///
448     /// # Examples
449     ///
450     /// Basic usage:
451     ///
452     /// ```no_run
453     /// use std::process::Command;
454     ///
455     /// Command::new("ls")
456     ///         .arg("-l")
457     ///         .arg("-a")
458     ///         .spawn()
459     ///         .expect("ls command failed to start");
460     /// ```
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());
464         self
465     }
466
467     /// Add multiple arguments to pass to the program.
468     ///
469     /// To pass a single argument see [`arg`].
470     ///
471     /// [`arg`]: #method.arg
472     ///
473     /// # Examples
474     ///
475     /// Basic usage:
476     ///
477     /// ```no_run
478     /// use std::process::Command;
479     ///
480     /// Command::new("ls")
481     ///         .args(&["-l", "-a"])
482     ///         .spawn()
483     ///         .expect("ls command failed to start");
484     /// ```
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>
488     {
489         for arg in args {
490             self.arg(arg.as_ref());
491         }
492         self
493     }
494
495     /// Inserts or updates an environment variable mapping.
496     ///
497     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
498     /// and case-sensitive on all other platforms.
499     ///
500     /// # Examples
501     ///
502     /// Basic usage:
503     ///
504     /// ```no_run
505     /// use std::process::Command;
506     ///
507     /// Command::new("ls")
508     ///         .env("PATH", "/bin")
509     ///         .spawn()
510     ///         .expect("ls command failed to start");
511     /// ```
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>
515     {
516         self.inner.env_mut().set(key.as_ref(), val.as_ref());
517         self
518     }
519
520     /// Add or update multiple environment variable mappings.
521     ///
522     /// # Examples
523     ///
524     /// Basic usage:
525     ///
526     /// ```no_run
527     /// use std::process::{Command, Stdio};
528     /// use std::env;
529     /// use std::collections::HashMap;
530     ///
531     /// let filtered_env : HashMap<String, String> =
532     ///     env::vars().filter(|&(ref k, _)|
533     ///         k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
534     ///     ).collect();
535     ///
536     /// Command::new("printenv")
537     ///         .stdin(Stdio::null())
538     ///         .stdout(Stdio::inherit())
539     ///         .env_clear()
540     ///         .envs(&filtered_env)
541     ///         .spawn()
542     ///         .expect("printenv failed to start");
543     /// ```
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>
547     {
548         for (ref key, ref val) in vars {
549             self.inner.env_mut().set(key.as_ref(), val.as_ref());
550         }
551         self
552     }
553
554     /// Removes an environment variable mapping.
555     ///
556     /// # Examples
557     ///
558     /// Basic usage:
559     ///
560     /// ```no_run
561     /// use std::process::Command;
562     ///
563     /// Command::new("ls")
564     ///         .env_remove("PATH")
565     ///         .spawn()
566     ///         .expect("ls command failed to start");
567     /// ```
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());
571         self
572     }
573
574     /// Clears the entire environment map for the child process.
575     ///
576     /// # Examples
577     ///
578     /// Basic usage:
579     ///
580     /// ```no_run
581     /// use std::process::Command;
582     ///
583     /// Command::new("ls")
584     ///         .env_clear()
585     ///         .spawn()
586     ///         .expect("ls command failed to start");
587     /// ```
588     #[stable(feature = "process", since = "1.0.0")]
589     pub fn env_clear(&mut self) -> &mut Command {
590         self.inner.env_mut().clear();
591         self
592     }
593
594     /// Sets the working directory for the child process.
595     ///
596     /// # Examples
597     ///
598     /// Basic usage:
599     ///
600     /// ```no_run
601     /// use std::process::Command;
602     ///
603     /// Command::new("ls")
604     ///         .current_dir("/bin")
605     ///         .spawn()
606     ///         .expect("ls command failed to start");
607     /// ```
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());
611         self
612     }
613
614     /// Configuration for the child process's standard input (stdin) handle.
615     ///
616     /// Defaults to [`inherit`] when used with `spawn` or `status`, and
617     /// defaults to [`piped`] when used with `output`.
618     ///
619     /// [`inherit`]: struct.Stdio.html#method.inherit
620     /// [`piped`]: struct.Stdio.html#method.piped
621     ///
622     /// # Examples
623     ///
624     /// Basic usage:
625     ///
626     /// ```no_run
627     /// use std::process::{Command, Stdio};
628     ///
629     /// Command::new("ls")
630     ///         .stdin(Stdio::null())
631     ///         .spawn()
632     ///         .expect("ls command failed to start");
633     /// ```
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);
637         self
638     }
639
640     /// Configuration for the child process's standard output (stdout) handle.
641     ///
642     /// Defaults to [`inherit`] when used with `spawn` or `status`, and
643     /// defaults to [`piped`] when used with `output`.
644     ///
645     /// [`inherit`]: struct.Stdio.html#method.inherit
646     /// [`piped`]: struct.Stdio.html#method.piped
647     ///
648     /// # Examples
649     ///
650     /// Basic usage:
651     ///
652     /// ```no_run
653     /// use std::process::{Command, Stdio};
654     ///
655     /// Command::new("ls")
656     ///         .stdout(Stdio::null())
657     ///         .spawn()
658     ///         .expect("ls command failed to start");
659     /// ```
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);
663         self
664     }
665
666     /// Configuration for the child process's standard error (stderr) handle.
667     ///
668     /// Defaults to [`inherit`] when used with `spawn` or `status`, and
669     /// defaults to [`piped`] when used with `output`.
670     ///
671     /// [`inherit`]: struct.Stdio.html#method.inherit
672     /// [`piped`]: struct.Stdio.html#method.piped
673     ///
674     /// # Examples
675     ///
676     /// Basic usage:
677     ///
678     /// ```no_run
679     /// use std::process::{Command, Stdio};
680     ///
681     /// Command::new("ls")
682     ///         .stderr(Stdio::null())
683     ///         .spawn()
684     ///         .expect("ls command failed to start");
685     /// ```
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);
689         self
690     }
691
692     /// Executes the command as a child process, returning a handle to it.
693     ///
694     /// By default, stdin, stdout and stderr are inherited from the parent.
695     ///
696     /// # Examples
697     ///
698     /// Basic usage:
699     ///
700     /// ```no_run
701     /// use std::process::Command;
702     ///
703     /// Command::new("ls")
704     ///         .spawn()
705     ///         .expect("ls command failed to start");
706     /// ```
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)
710     }
711
712     /// Executes the command as a child process, waiting for it to finish and
713     /// collecting all of its output.
714     ///
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.
719     ///
720     /// # Examples
721     ///
722     /// ```should_panic
723     /// use std::process::Command;
724     /// let output = Command::new("/bin/cat")
725     ///                      .arg("file.txt")
726     ///                      .output()
727     ///                      .expect("failed to execute process");
728     ///
729     /// println!("status: {}", output.status);
730     /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
731     /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
732     ///
733     /// assert!(output.status.success());
734     /// ```
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())
739     }
740
741     /// Executes a command as a child process, waiting for it to finish and
742     /// collecting its exit status.
743     ///
744     /// By default, stdin, stdout and stderr are inherited from the parent.
745     ///
746     /// # Examples
747     ///
748     /// ```should_panic
749     /// use std::process::Command;
750     ///
751     /// let status = Command::new("/bin/cat")
752     ///                      .arg("file.txt")
753     ///                      .status()
754     ///                      .expect("failed to execute process");
755     ///
756     /// println!("process exited with: {}", status);
757     ///
758     /// assert!(status.success());
759     /// ```
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())
764     }
765 }
766
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
771     /// character.
772     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
773         self.inner.fmt(f)
774     }
775 }
776
777 impl AsInner<imp::Command> for Command {
778     fn as_inner(&self) -> &imp::Command { &self.inner }
779 }
780
781 impl AsInnerMut<imp::Command> for Command {
782     fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
783 }
784
785 /// The output of a finished process.
786 ///
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`]
789 /// process.
790 ///
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")]
797 pub struct Output {
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")]
803     pub stdout: Vec<u8>,
804     /// The data that the process wrote to stderr.
805     #[stable(feature = "process", since = "1.0.0")]
806     pub stderr: Vec<u8>,
807 }
808
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 {
814
815         let stdout_utf8 = str::from_utf8(&self.stdout);
816         let stdout_debug: &fmt::Debug = match stdout_utf8 {
817             Ok(ref str) => str,
818             Err(_) => &self.stdout
819         };
820
821         let stderr_utf8 = str::from_utf8(&self.stderr);
822         let stderr_debug: &fmt::Debug = match stderr_utf8 {
823             Ok(ref str) => str,
824             Err(_) => &self.stderr
825         };
826
827         fmt.debug_struct("Output")
828             .field("status", &self.status)
829             .field("stdout", stdout_debug)
830             .field("stderr", stderr_debug)
831             .finish()
832     }
833 }
834
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`].
837 ///
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);
844
845 impl Stdio {
846     /// A new pipe should be arranged to connect the parent and child processes.
847     ///
848     /// # Examples
849     ///
850     /// With stdout:
851     ///
852     /// ```no_run
853     /// use std::process::{Command, Stdio};
854     ///
855     /// let output = Command::new("echo")
856     ///     .arg("Hello, world!")
857     ///     .stdout(Stdio::piped())
858     ///     .output()
859     ///     .expect("Failed to execute command");
860     ///
861     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
862     /// // Nothing echoed to console
863     /// ```
864     ///
865     /// With stdin:
866     ///
867     /// ```no_run
868     /// use std::io::Write;
869     /// use std::process::{Command, Stdio};
870     ///
871     /// let mut child = Command::new("rev")
872     ///     .stdin(Stdio::piped())
873     ///     .stdout(Stdio::piped())
874     ///     .spawn()
875     ///     .expect("Failed to spawn child process");
876     ///
877     /// {
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");
880     /// }
881     ///
882     /// let output = child.wait_with_output().expect("Failed to read stdout");
883     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
884     /// ```
885     #[stable(feature = "process", since = "1.0.0")]
886     pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
887
888     /// The child inherits from the corresponding parent descriptor.
889     ///
890     /// # Examples
891     ///
892     /// With stdout:
893     ///
894     /// ```no_run
895     /// use std::process::{Command, Stdio};
896     ///
897     /// let output = Command::new("echo")
898     ///     .arg("Hello, world!")
899     ///     .stdout(Stdio::inherit())
900     ///     .output()
901     ///     .expect("Failed to execute command");
902     ///
903     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
904     /// // "Hello, world!" echoed to console
905     /// ```
906     ///
907     /// With stdin:
908     ///
909     /// ```no_run
910     /// use std::process::{Command, Stdio};
911     ///
912     /// let output = Command::new("rev")
913     ///     .stdin(Stdio::inherit())
914     ///     .stdout(Stdio::piped())
915     ///     .output()
916     ///     .expect("Failed to execute command");
917     ///
918     /// println!("You piped in the reverse of: {}", String::from_utf8_lossy(&output.stdout));
919     /// ```
920     #[stable(feature = "process", since = "1.0.0")]
921     pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
922
923     /// This stream will be ignored. This is the equivalent of attaching the
924     /// stream to `/dev/null`
925     ///
926     /// # Examples
927     ///
928     /// With stdout:
929     ///
930     /// ```no_run
931     /// use std::process::{Command, Stdio};
932     ///
933     /// let output = Command::new("echo")
934     ///     .arg("Hello, world!")
935     ///     .stdout(Stdio::null())
936     ///     .output()
937     ///     .expect("Failed to execute command");
938     ///
939     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
940     /// // Nothing echoed to console
941     /// ```
942     ///
943     /// With stdin:
944     ///
945     /// ```no_run
946     /// use std::process::{Command, Stdio};
947     ///
948     /// let output = Command::new("rev")
949     ///     .stdin(Stdio::null())
950     ///     .stdout(Stdio::piped())
951     ///     .output()
952     ///     .expect("Failed to execute command");
953     ///
954     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
955     /// // Ignores any piped-in input
956     /// ```
957     #[stable(feature = "process", since = "1.0.0")]
958     pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
959 }
960
961 impl FromInner<imp::Stdio> for Stdio {
962     fn from_inner(inner: imp::Stdio) -> Stdio {
963         Stdio(inner)
964     }
965 }
966
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 { .. }")
971     }
972 }
973
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())
978     }
979 }
980
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())
985     }
986 }
987
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())
992     }
993 }
994
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())
999     }
1000 }
1001
1002 /// Describes the result of a process after it has terminated.
1003 ///
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.
1007 ///
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);
1013
1014 impl ExitStatus {
1015     /// Was termination successful? Signal termination is not considered a
1016     /// success, and success is defined as a zero exit status.
1017     ///
1018     /// # Examples
1019     ///
1020     /// ```rust,no_run
1021     /// use std::process::Command;
1022     ///
1023     /// let status = Command::new("mkdir")
1024     ///                      .arg("projects")
1025     ///                      .status()
1026     ///                      .expect("failed to execute mkdir");
1027     ///
1028     /// if status.success() {
1029     ///     println!("'projects/' directory created");
1030     /// } else {
1031     ///     println!("failed to create 'projects/' directory");
1032     /// }
1033     /// ```
1034     #[stable(feature = "process", since = "1.0.0")]
1035     pub fn success(&self) -> bool {
1036         self.0.success()
1037     }
1038
1039     /// Returns the exit code of the process, if any.
1040     ///
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`.
1044     ///
1045     /// # Examples
1046     ///
1047     /// ```no_run
1048     /// use std::process::Command;
1049     ///
1050     /// let status = Command::new("mkdir")
1051     ///                      .arg("projects")
1052     ///                      .status()
1053     ///                      .expect("failed to execute mkdir");
1054     ///
1055     /// match status.code() {
1056     ///     Some(code) => println!("Exited with status code: {}", code),
1057     ///     None       => println!("Process terminated by signal")
1058     /// }
1059     /// ```
1060     #[stable(feature = "process", since = "1.0.0")]
1061     pub fn code(&self) -> Option<i32> {
1062         self.0.code()
1063     }
1064 }
1065
1066 impl AsInner<imp::ExitStatus> for ExitStatus {
1067     fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
1068 }
1069
1070 impl FromInner<imp::ExitStatus> for ExitStatus {
1071     fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1072         ExitStatus(s)
1073     }
1074 }
1075
1076 #[stable(feature = "process", since = "1.0.0")]
1077 impl fmt::Display for ExitStatus {
1078     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1079         self.0.fmt(f)
1080     }
1081 }
1082
1083 /// This type represents the status code a process can return to its
1084 /// parent under normal termination.
1085 ///
1086 /// Numeric values used in this type don't have portable meanings, and
1087 /// different platforms may mask different amounts of them.
1088 ///
1089 /// For the platform's canonical successful and unsuccessful codes, see
1090 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1091 ///
1092 /// [`SUCCESS`]: #associatedconstant.SUCCESS
1093 /// [`FAILURE`]: #associatedconstant.FAILURE
1094 ///
1095 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1096 /// it was ultimately cut from that RFC, and thus this type is more subject
1097 /// to change even than the usual unstable item churn.
1098 ///
1099 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1100 #[derive(Clone, Copy, Debug)]
1101 #[unstable(feature = "process_exitcode_placeholder", issue = "43301")]
1102 pub struct ExitCode(pub i32);
1103
1104 #[cfg(target_arch = "wasm32")]
1105 mod rawexit {
1106     pub const SUCCESS: i32 = 0;
1107     pub const FAILURE: i32 = 1;
1108 }
1109 #[cfg(not(target_arch = "wasm32"))]
1110 mod rawexit {
1111     use libc;
1112     pub const SUCCESS: i32 = libc::EXIT_SUCCESS;
1113     pub const FAILURE: i32 = libc::EXIT_FAILURE;
1114 }
1115
1116 #[unstable(feature = "process_exitcode_placeholder", issue = "43301")]
1117 impl ExitCode {
1118     /// The canonical ExitCode for successful termination on this platform.
1119     ///
1120     /// Note that a `()`-returning `main` implicitly results in a successful
1121     /// termination, so there's no need to return this from `main` unless
1122     /// you're also returning other possible codes.
1123     #[unstable(feature = "process_exitcode_placeholder", issue = "43301")]
1124     pub const SUCCESS: ExitCode = ExitCode(rawexit::SUCCESS);
1125
1126     /// The canonical ExitCode for unsuccessful termination on this platform.
1127     ///
1128     /// If you're only returning this and `SUCCESS` from `main`, consider
1129     /// instead returning `Err(_)` and `Ok(())` respectively, which will
1130     /// return the same codes (but will also `eprintln!` the error).
1131     #[unstable(feature = "process_exitcode_placeholder", issue = "43301")]
1132     pub const FAILURE: ExitCode = ExitCode(rawexit::FAILURE);
1133 }
1134
1135 impl Child {
1136     /// Forces the child to exit. This is equivalent to sending a
1137     /// SIGKILL on unix platforms.
1138     ///
1139     /// # Examples
1140     ///
1141     /// Basic usage:
1142     ///
1143     /// ```no_run
1144     /// use std::process::Command;
1145     ///
1146     /// let mut command = Command::new("yes");
1147     /// if let Ok(mut child) = command.spawn() {
1148     ///     child.kill().expect("command wasn't running");
1149     /// } else {
1150     ///     println!("yes command didn't start");
1151     /// }
1152     /// ```
1153     #[stable(feature = "process", since = "1.0.0")]
1154     pub fn kill(&mut self) -> io::Result<()> {
1155         self.handle.kill()
1156     }
1157
1158     /// Returns the OS-assigned process identifier associated with this child.
1159     ///
1160     /// # Examples
1161     ///
1162     /// Basic usage:
1163     ///
1164     /// ```no_run
1165     /// use std::process::Command;
1166     ///
1167     /// let mut command = Command::new("ls");
1168     /// if let Ok(child) = command.spawn() {
1169     ///     println!("Child's id is {}", child.id());
1170     /// } else {
1171     ///     println!("ls command didn't start");
1172     /// }
1173     /// ```
1174     #[stable(feature = "process_id", since = "1.3.0")]
1175     pub fn id(&self) -> u32 {
1176         self.handle.id()
1177     }
1178
1179     /// Waits for the child to exit completely, returning the status that it
1180     /// exited with. This function will continue to have the same return value
1181     /// after it has been called at least once.
1182     ///
1183     /// The stdin handle to the child process, if any, will be closed
1184     /// before waiting. This helps avoid deadlock: it ensures that the
1185     /// child does not block waiting for input from the parent, while
1186     /// the parent waits for the child to exit.
1187     ///
1188     /// # Examples
1189     ///
1190     /// Basic usage:
1191     ///
1192     /// ```no_run
1193     /// use std::process::Command;
1194     ///
1195     /// let mut command = Command::new("ls");
1196     /// if let Ok(mut child) = command.spawn() {
1197     ///     child.wait().expect("command wasn't running");
1198     ///     println!("Child has finished its execution!");
1199     /// } else {
1200     ///     println!("ls command didn't start");
1201     /// }
1202     /// ```
1203     #[stable(feature = "process", since = "1.0.0")]
1204     pub fn wait(&mut self) -> io::Result<ExitStatus> {
1205         drop(self.stdin.take());
1206         self.handle.wait().map(ExitStatus)
1207     }
1208
1209     /// Attempts to collect the exit status of the child if it has already
1210     /// exited.
1211     ///
1212     /// This function will not block the calling thread and will only advisorily
1213     /// check to see if the child process has exited or not. If the child has
1214     /// exited then on Unix the process id is reaped. This function is
1215     /// guaranteed to repeatedly return a successful exit status so long as the
1216     /// child has already exited.
1217     ///
1218     /// If the child has exited, then `Ok(Some(status))` is returned. If the
1219     /// exit status is not available at this time then `Ok(None)` is returned.
1220     /// If an error occurs, then that error is returned.
1221     ///
1222     /// Note that unlike `wait`, this function will not attempt to drop stdin.
1223     ///
1224     /// # Examples
1225     ///
1226     /// Basic usage:
1227     ///
1228     /// ```no_run
1229     /// use std::process::Command;
1230     ///
1231     /// let mut child = Command::new("ls").spawn().unwrap();
1232     ///
1233     /// match child.try_wait() {
1234     ///     Ok(Some(status)) => println!("exited with: {}", status),
1235     ///     Ok(None) => {
1236     ///         println!("status not ready yet, let's really wait");
1237     ///         let res = child.wait();
1238     ///         println!("result: {:?}", res);
1239     ///     }
1240     ///     Err(e) => println!("error attempting to wait: {}", e),
1241     /// }
1242     /// ```
1243     #[stable(feature = "process_try_wait", since = "1.18.0")]
1244     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1245         Ok(self.handle.try_wait()?.map(ExitStatus))
1246     }
1247
1248     /// Simultaneously waits for the child to exit and collect all remaining
1249     /// output on the stdout/stderr handles, returning an `Output`
1250     /// instance.
1251     ///
1252     /// The stdin handle to the child process, if any, will be closed
1253     /// before waiting. This helps avoid deadlock: it ensures that the
1254     /// child does not block waiting for input from the parent, while
1255     /// the parent waits for the child to exit.
1256     ///
1257     /// By default, stdin, stdout and stderr are inherited from the parent.
1258     /// In order to capture the output into this `Result<Output>` it is
1259     /// necessary to create new pipes between parent and child. Use
1260     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1261     ///
1262     /// # Examples
1263     ///
1264     /// ```should_panic
1265     /// use std::process::{Command, Stdio};
1266     ///
1267     /// let child = Command::new("/bin/cat")
1268     ///     .arg("file.txt")
1269     ///     .stdout(Stdio::piped())
1270     ///     .spawn()
1271     ///     .expect("failed to execute child");
1272     ///
1273     /// let output = child
1274     ///     .wait_with_output()
1275     ///     .expect("failed to wait on child");
1276     ///
1277     /// assert!(output.status.success());
1278     /// ```
1279     ///
1280     #[stable(feature = "process", since = "1.0.0")]
1281     pub fn wait_with_output(mut self) -> io::Result<Output> {
1282         drop(self.stdin.take());
1283
1284         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1285         match (self.stdout.take(), self.stderr.take()) {
1286             (None, None) => {}
1287             (Some(mut out), None) => {
1288                 let res = out.read_to_end(&mut stdout);
1289                 res.unwrap();
1290             }
1291             (None, Some(mut err)) => {
1292                 let res = err.read_to_end(&mut stderr);
1293                 res.unwrap();
1294             }
1295             (Some(out), Some(err)) => {
1296                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1297                 res.unwrap();
1298             }
1299         }
1300
1301         let status = self.wait()?;
1302         Ok(Output {
1303             status,
1304             stdout,
1305             stderr,
1306         })
1307     }
1308 }
1309
1310 /// Terminates the current process with the specified exit code.
1311 ///
1312 /// This function will never return and will immediately terminate the current
1313 /// process. The exit code is passed through to the underlying OS and will be
1314 /// available for consumption by another process.
1315 ///
1316 /// Note that because this function never returns, and that it terminates the
1317 /// process, no destructors on the current stack or any other thread's stack
1318 /// will be run. If a clean shutdown is needed it is recommended to only call
1319 /// this function at a known point where there are no more destructors left
1320 /// to run.
1321 ///
1322 /// ## Platform-specific behavior
1323 ///
1324 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1325 /// will be visible to a parent process inspecting the exit code. On most
1326 /// Unix-like platforms, only the eight least-significant bits are considered.
1327 ///
1328 /// # Examples
1329 ///
1330 /// Due to this function’s behavior regarding destructors, a conventional way
1331 /// to use the function is to extract the actual computation to another
1332 /// function and compute the exit code from its return value:
1333 ///
1334 /// ```
1335 /// fn run_app() -> Result<(), ()> {
1336 ///     // Application logic here
1337 ///     Ok(())
1338 /// }
1339 ///
1340 /// fn main() {
1341 ///     ::std::process::exit(match run_app() {
1342 ///        Ok(_) => 0,
1343 ///        Err(err) => {
1344 ///            eprintln!("error: {:?}", err);
1345 ///            1
1346 ///        }
1347 ///     });
1348 /// }
1349 /// ```
1350 ///
1351 /// Due to [platform-specific behavior], the exit code for this example will be
1352 /// `0` on Linux, but `256` on Windows:
1353 ///
1354 /// ```no_run
1355 /// use std::process;
1356 ///
1357 /// process::exit(0x0100);
1358 /// ```
1359 ///
1360 /// [platform-specific behavior]: #platform-specific-behavior
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 pub fn exit(code: i32) -> ! {
1363     ::sys_common::cleanup();
1364     ::sys::os::exit(code)
1365 }
1366
1367 /// Terminates the process in an abnormal fashion.
1368 ///
1369 /// The function will never return and will immediately terminate the current
1370 /// process in a platform specific "abnormal" manner.
1371 ///
1372 /// Note that because this function never returns, and that it terminates the
1373 /// process, no destructors on the current stack or any other thread's stack
1374 /// will be run.
1375 ///
1376 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1377 /// the current thread's stack and calls all destructors.
1378 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1379 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1380 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1381 ///
1382 /// If a clean shutdown is needed it is recommended to only call
1383 /// this function at a known point where there are no more destructors left
1384 /// to run.
1385 ///
1386 /// # Examples
1387 ///
1388 /// ```no_run
1389 /// use std::process;
1390 ///
1391 /// fn main() {
1392 ///     println!("aborting");
1393 ///
1394 ///     process::abort();
1395 ///
1396 ///     // execution never gets here
1397 /// }
1398 /// ```
1399 ///
1400 /// The `abort` function terminates the process, so the destructor will not
1401 /// get run on the example below:
1402 ///
1403 /// ```no_run
1404 /// use std::process;
1405 ///
1406 /// struct HasDrop;
1407 ///
1408 /// impl Drop for HasDrop {
1409 ///     fn drop(&mut self) {
1410 ///         println!("This will never be printed!");
1411 ///     }
1412 /// }
1413 ///
1414 /// fn main() {
1415 ///     let _x = HasDrop;
1416 ///     process::abort();
1417 ///     // the destructor implemented for HasDrop will never get run
1418 /// }
1419 /// ```
1420 ///
1421 /// [`panic!`]: ../../std/macro.panic.html
1422 /// [panic hook]: ../../std/panic/fn.set_hook.html
1423 #[stable(feature = "process_abort", since = "1.17.0")]
1424 pub fn abort() -> ! {
1425     unsafe { ::sys::abort_internal() };
1426 }
1427
1428 /// Returns the OS-assigned process identifier associated with this process.
1429 ///
1430 /// # Examples
1431 ///
1432 /// Basic usage:
1433 ///
1434 /// ```no_run
1435 /// #![feature(getpid)]
1436 /// use std::process;
1437 ///
1438 /// println!("My pid is {}", process::id());
1439 /// ```
1440 ///
1441 ///
1442 #[unstable(feature = "getpid", issue = "44971", reason = "recently added")]
1443 pub fn id() -> u32 {
1444     ::sys::os::getpid()
1445 }
1446
1447 /// A trait for implementing arbitrary return types in the `main` function.
1448 ///
1449 /// The c-main function only supports to return integers as return type.
1450 /// So, every type implementing the `Termination` trait has to be converted
1451 /// to an integer.
1452 ///
1453 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1454 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1455 #[cfg_attr(not(test), lang = "termination")]
1456 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1457 #[rustc_on_unimplemented =
1458   "`main` can only return types that implement {Termination}, not `{Self}`"]
1459 pub trait Termination {
1460     /// Is called to get the representation of the value as status code.
1461     /// This status code is returned to the operating system.
1462     fn report(self) -> i32;
1463 }
1464
1465 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1466 impl Termination for () {
1467     fn report(self) -> i32 { ExitCode::SUCCESS.report() }
1468 }
1469
1470 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1471 impl<E: fmt::Debug> Termination for Result<(), E> {
1472     fn report(self) -> i32 {
1473         match self {
1474             Ok(()) => ().report(),
1475             Err(err) => Err::<!, _>(err).report(),
1476         }
1477     }
1478 }
1479
1480 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1481 impl Termination for ! {
1482     fn report(self) -> i32 { self }
1483 }
1484
1485 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1486 impl<E: fmt::Debug> Termination for Result<!, E> {
1487     fn report(self) -> i32 {
1488         let Err(err) = self;
1489         eprintln!("Error: {:?}", err);
1490         ExitCode::FAILURE.report()
1491     }
1492 }
1493
1494 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1495 impl Termination for ExitCode {
1496     fn report(self) -> i32 {
1497         let ExitCode(code) = self;
1498         code
1499     }
1500 }
1501
1502 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
1503 mod tests {
1504     use io::prelude::*;
1505
1506     use io::ErrorKind;
1507     use str;
1508     use super::{Command, Output, Stdio};
1509
1510     // FIXME(#10380) these tests should not all be ignored on android.
1511
1512     #[test]
1513     #[cfg_attr(target_os = "android", ignore)]
1514     fn smoke() {
1515         let p = if cfg!(target_os = "windows") {
1516             Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1517         } else {
1518             Command::new("true").spawn()
1519         };
1520         assert!(p.is_ok());
1521         let mut p = p.unwrap();
1522         assert!(p.wait().unwrap().success());
1523     }
1524
1525     #[test]
1526     #[cfg_attr(target_os = "android", ignore)]
1527     fn smoke_failure() {
1528         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1529             Ok(..) => panic!(),
1530             Err(..) => {}
1531         }
1532     }
1533
1534     #[test]
1535     #[cfg_attr(target_os = "android", ignore)]
1536     fn exit_reported_right() {
1537         let p = if cfg!(target_os = "windows") {
1538             Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1539         } else {
1540             Command::new("false").spawn()
1541         };
1542         assert!(p.is_ok());
1543         let mut p = p.unwrap();
1544         assert!(p.wait().unwrap().code() == Some(1));
1545         drop(p.wait());
1546     }
1547
1548     #[test]
1549     #[cfg(unix)]
1550     #[cfg_attr(target_os = "android", ignore)]
1551     fn signal_reported_right() {
1552         use os::unix::process::ExitStatusExt;
1553
1554         let mut p = Command::new("/bin/sh")
1555                             .arg("-c").arg("read a")
1556                             .stdin(Stdio::piped())
1557                             .spawn().unwrap();
1558         p.kill().unwrap();
1559         match p.wait().unwrap().signal() {
1560             Some(9) => {},
1561             result => panic!("not terminated by signal 9 (instead, {:?})",
1562                              result),
1563         }
1564     }
1565
1566     pub fn run_output(mut cmd: Command) -> String {
1567         let p = cmd.spawn();
1568         assert!(p.is_ok());
1569         let mut p = p.unwrap();
1570         assert!(p.stdout.is_some());
1571         let mut ret = String::new();
1572         p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1573         assert!(p.wait().unwrap().success());
1574         return ret;
1575     }
1576
1577     #[test]
1578     #[cfg_attr(target_os = "android", ignore)]
1579     fn stdout_works() {
1580         if cfg!(target_os = "windows") {
1581             let mut cmd = Command::new("cmd");
1582             cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1583             assert_eq!(run_output(cmd), "foobar\r\n");
1584         } else {
1585             let mut cmd = Command::new("echo");
1586             cmd.arg("foobar").stdout(Stdio::piped());
1587             assert_eq!(run_output(cmd), "foobar\n");
1588         }
1589     }
1590
1591     #[test]
1592     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1593     fn set_current_dir_works() {
1594         let mut cmd = Command::new("/bin/sh");
1595         cmd.arg("-c").arg("pwd")
1596            .current_dir("/")
1597            .stdout(Stdio::piped());
1598         assert_eq!(run_output(cmd), "/\n");
1599     }
1600
1601     #[test]
1602     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1603     fn stdin_works() {
1604         let mut p = Command::new("/bin/sh")
1605                             .arg("-c").arg("read line; echo $line")
1606                             .stdin(Stdio::piped())
1607                             .stdout(Stdio::piped())
1608                             .spawn().unwrap();
1609         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1610         drop(p.stdin.take());
1611         let mut out = String::new();
1612         p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1613         assert!(p.wait().unwrap().success());
1614         assert_eq!(out, "foobar\n");
1615     }
1616
1617
1618     #[test]
1619     #[cfg_attr(target_os = "android", ignore)]
1620     #[cfg(unix)]
1621     fn uid_works() {
1622         use os::unix::prelude::*;
1623         use libc;
1624         let mut p = Command::new("/bin/sh")
1625                             .arg("-c").arg("true")
1626                             .uid(unsafe { libc::getuid() })
1627                             .gid(unsafe { libc::getgid() })
1628                             .spawn().unwrap();
1629         assert!(p.wait().unwrap().success());
1630     }
1631
1632     #[test]
1633     #[cfg_attr(target_os = "android", ignore)]
1634     #[cfg(unix)]
1635     fn uid_to_root_fails() {
1636         use os::unix::prelude::*;
1637         use libc;
1638
1639         // if we're already root, this isn't a valid test. Most of the bots run
1640         // as non-root though (android is an exception).
1641         if unsafe { libc::getuid() == 0 } { return }
1642         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1643     }
1644
1645     #[test]
1646     #[cfg_attr(target_os = "android", ignore)]
1647     fn test_process_status() {
1648         let mut status = if cfg!(target_os = "windows") {
1649             Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1650         } else {
1651             Command::new("false").status().unwrap()
1652         };
1653         assert!(status.code() == Some(1));
1654
1655         status = if cfg!(target_os = "windows") {
1656             Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1657         } else {
1658             Command::new("true").status().unwrap()
1659         };
1660         assert!(status.success());
1661     }
1662
1663     #[test]
1664     fn test_process_output_fail_to_start() {
1665         match Command::new("/no-binary-by-this-name-should-exist").output() {
1666             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1667             Ok(..) => panic!()
1668         }
1669     }
1670
1671     #[test]
1672     #[cfg_attr(target_os = "android", ignore)]
1673     fn test_process_output_output() {
1674         let Output {status, stdout, stderr}
1675              = if cfg!(target_os = "windows") {
1676                  Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1677              } else {
1678                  Command::new("echo").arg("hello").output().unwrap()
1679              };
1680         let output_str = str::from_utf8(&stdout).unwrap();
1681
1682         assert!(status.success());
1683         assert_eq!(output_str.trim().to_string(), "hello");
1684         assert_eq!(stderr, Vec::new());
1685     }
1686
1687     #[test]
1688     #[cfg_attr(target_os = "android", ignore)]
1689     fn test_process_output_error() {
1690         let Output {status, stdout, stderr}
1691              = if cfg!(target_os = "windows") {
1692                  Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1693              } else {
1694                  Command::new("mkdir").arg("./").output().unwrap()
1695              };
1696
1697         assert!(status.code() == Some(1));
1698         assert_eq!(stdout, Vec::new());
1699         assert!(!stderr.is_empty());
1700     }
1701
1702     #[test]
1703     #[cfg_attr(target_os = "android", ignore)]
1704     fn test_finish_once() {
1705         let mut prog = if cfg!(target_os = "windows") {
1706             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1707         } else {
1708             Command::new("false").spawn().unwrap()
1709         };
1710         assert!(prog.wait().unwrap().code() == Some(1));
1711     }
1712
1713     #[test]
1714     #[cfg_attr(target_os = "android", ignore)]
1715     fn test_finish_twice() {
1716         let mut prog = if cfg!(target_os = "windows") {
1717             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1718         } else {
1719             Command::new("false").spawn().unwrap()
1720         };
1721         assert!(prog.wait().unwrap().code() == Some(1));
1722         assert!(prog.wait().unwrap().code() == Some(1));
1723     }
1724
1725     #[test]
1726     #[cfg_attr(target_os = "android", ignore)]
1727     fn test_wait_with_output_once() {
1728         let prog = if cfg!(target_os = "windows") {
1729             Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1730         } else {
1731             Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1732         };
1733
1734         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1735         let output_str = str::from_utf8(&stdout).unwrap();
1736
1737         assert!(status.success());
1738         assert_eq!(output_str.trim().to_string(), "hello");
1739         assert_eq!(stderr, Vec::new());
1740     }
1741
1742     #[cfg(all(unix, not(target_os="android")))]
1743     pub fn env_cmd() -> Command {
1744         Command::new("env")
1745     }
1746     #[cfg(target_os="android")]
1747     pub fn env_cmd() -> Command {
1748         let mut cmd = Command::new("/system/bin/sh");
1749         cmd.arg("-c").arg("set");
1750         cmd
1751     }
1752
1753     #[cfg(windows)]
1754     pub fn env_cmd() -> Command {
1755         let mut cmd = Command::new("cmd");
1756         cmd.arg("/c").arg("set");
1757         cmd
1758     }
1759
1760     #[test]
1761     fn test_inherit_env() {
1762         use env;
1763
1764         let result = env_cmd().output().unwrap();
1765         let output = String::from_utf8(result.stdout).unwrap();
1766
1767         for (ref k, ref v) in env::vars() {
1768             // Don't check android RANDOM variable which seems to change
1769             // whenever the shell runs, and our `env_cmd` is indeed running a
1770             // shell which means it'll get a different RANDOM than we probably
1771             // have.
1772             //
1773             // Also skip env vars with `-` in the name on android because, well,
1774             // I'm not sure. It appears though that the `set` command above does
1775             // not print env vars with `-` in the name, so we just skip them
1776             // here as we won't find them in the output. Note that most env vars
1777             // use `_` instead of `-`, but our build system sets a few env vars
1778             // with `-` in the name.
1779             if cfg!(target_os = "android") &&
1780                (*k == "RANDOM" || k.contains("-")) {
1781                 continue
1782             }
1783
1784             // Windows has hidden environment variables whose names start with
1785             // equals signs (`=`). Those do not show up in the output of the
1786             // `set` command.
1787             assert!((cfg!(windows) && k.starts_with("=")) ||
1788                     k.starts_with("DYLD") ||
1789                     output.contains(&format!("{}={}", *k, *v)) ||
1790                     output.contains(&format!("{}='{}'", *k, *v)),
1791                     "output doesn't contain `{}={}`\n{}",
1792                     k, v, output);
1793         }
1794     }
1795
1796     #[test]
1797     fn test_override_env() {
1798         use env;
1799
1800         // In some build environments (such as chrooted Nix builds), `env` can
1801         // only be found in the explicitly-provided PATH env variable, not in
1802         // default places such as /bin or /usr/bin. So we need to pass through
1803         // PATH to our sub-process.
1804         let mut cmd = env_cmd();
1805         cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1806         if let Some(p) = env::var_os("PATH") {
1807             cmd.env("PATH", &p);
1808         }
1809         let result = cmd.output().unwrap();
1810         let output = String::from_utf8_lossy(&result.stdout).to_string();
1811
1812         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1813                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1814     }
1815
1816     #[test]
1817     fn test_add_to_env() {
1818         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1819         let output = String::from_utf8_lossy(&result.stdout).to_string();
1820
1821         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1822                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1823     }
1824
1825     #[test]
1826     fn test_capture_env_at_spawn() {
1827         use env;
1828
1829         let mut cmd = env_cmd();
1830         cmd.env("RUN_TEST_NEW_ENV1", "123");
1831
1832         // This variable will not be present if the environment has already
1833         // been captured above.
1834         env::set_var("RUN_TEST_NEW_ENV2", "456");
1835         let result = cmd.output().unwrap();
1836         env::remove_var("RUN_TEST_NEW_ENV2");
1837
1838         let output = String::from_utf8_lossy(&result.stdout).to_string();
1839
1840         assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1841                 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1842         assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1843                 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1844     }
1845
1846     // Regression tests for #30858.
1847     #[test]
1848     fn test_interior_nul_in_progname_is_error() {
1849         match Command::new("has-some-\0\0s-inside").spawn() {
1850             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1851             Ok(_) => panic!(),
1852         }
1853     }
1854
1855     #[test]
1856     fn test_interior_nul_in_arg_is_error() {
1857         match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1858             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1859             Ok(_) => panic!(),
1860         }
1861     }
1862
1863     #[test]
1864     fn test_interior_nul_in_args_is_error() {
1865         match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1866             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1867             Ok(_) => panic!(),
1868         }
1869     }
1870
1871     #[test]
1872     fn test_interior_nul_in_current_dir_is_error() {
1873         match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1874             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1875             Ok(_) => panic!(),
1876         }
1877     }
1878
1879     // Regression tests for #30862.
1880     #[test]
1881     fn test_interior_nul_in_env_key_is_error() {
1882         match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1883             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1884             Ok(_) => panic!(),
1885         }
1886     }
1887
1888     #[test]
1889     fn test_interior_nul_in_env_value_is_error() {
1890         match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1891             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1892             Ok(_) => panic!(),
1893         }
1894     }
1895
1896     /// Test that process creation flags work by debugging a process.
1897     /// Other creation flags make it hard or impossible to detect
1898     /// behavioral changes in the process.
1899     #[test]
1900     #[cfg(windows)]
1901     fn test_creation_flags() {
1902         use os::windows::process::CommandExt;
1903         use sys::c::{BOOL, DWORD, INFINITE};
1904         #[repr(C, packed)]
1905         struct DEBUG_EVENT {
1906             pub event_code: DWORD,
1907             pub process_id: DWORD,
1908             pub thread_id: DWORD,
1909             // This is a union in the real struct, but we don't
1910             // need this data for the purposes of this test.
1911             pub _junk: [u8; 164],
1912         }
1913
1914         extern "system" {
1915             fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1916             fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1917                                   dwContinueStatus: DWORD) -> BOOL;
1918         }
1919
1920         const DEBUG_PROCESS: DWORD = 1;
1921         const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1922         const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1923
1924         let mut child = Command::new("cmd")
1925             .creation_flags(DEBUG_PROCESS)
1926             .stdin(Stdio::piped()).spawn().unwrap();
1927         child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1928         let mut events = 0;
1929         let mut event = DEBUG_EVENT {
1930             event_code: 0,
1931             process_id: 0,
1932             thread_id: 0,
1933             _junk: [0; 164],
1934         };
1935         loop {
1936             if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1937                 panic!("WaitForDebugEvent failed!");
1938             }
1939             events += 1;
1940
1941             if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1942                 break;
1943             }
1944
1945             if unsafe { ContinueDebugEvent(event.process_id,
1946                                            event.thread_id,
1947                                            DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1948                 panic!("ContinueDebugEvent failed!");
1949             }
1950         }
1951         assert!(events > 0);
1952     }
1953
1954     #[test]
1955     fn test_command_implements_send() {
1956         fn take_send_type<T: Send>(_: T) {}
1957         take_send_type(Command::new(""))
1958     }
1959 }