]> git.lizzy.rs Git - rust.git/blob - src/libstd/process.rs
Rollup merge of #52769 - sinkuu:stray_test, r=alexcrichton
[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: &dyn 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: &dyn 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 = "48711")]
1102 pub struct ExitCode(imp::ExitCode);
1103
1104 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1105 impl ExitCode {
1106     /// The canonical ExitCode for successful termination on this platform.
1107     ///
1108     /// Note that a `()`-returning `main` implicitly results in a successful
1109     /// termination, so there's no need to return this from `main` unless
1110     /// you're also returning other possible codes.
1111     #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1112     pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1113
1114     /// The canonical ExitCode for unsuccessful termination on this platform.
1115     ///
1116     /// If you're only returning this and `SUCCESS` from `main`, consider
1117     /// instead returning `Err(_)` and `Ok(())` respectively, which will
1118     /// return the same codes (but will also `eprintln!` the error).
1119     #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1120     pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1121 }
1122
1123 impl Child {
1124     /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1125     /// error is returned.
1126     ///
1127     /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
1128     /// especially the [`Other`] kind might change to more specific kinds in the future.
1129     ///
1130     /// This is equivalent to sending a SIGKILL on Unix platforms.
1131     ///
1132     /// # Examples
1133     ///
1134     /// Basic usage:
1135     ///
1136     /// ```no_run
1137     /// use std::process::Command;
1138     ///
1139     /// let mut command = Command::new("yes");
1140     /// if let Ok(mut child) = command.spawn() {
1141     ///     child.kill().expect("command wasn't running");
1142     /// } else {
1143     ///     println!("yes command didn't start");
1144     /// }
1145     /// ```
1146     ///
1147     /// [`ErrorKind`]: ../io/enum.ErrorKind.html
1148     /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
1149     /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
1150     #[stable(feature = "process", since = "1.0.0")]
1151     pub fn kill(&mut self) -> io::Result<()> {
1152         self.handle.kill()
1153     }
1154
1155     /// Returns the OS-assigned process identifier associated with this child.
1156     ///
1157     /// # Examples
1158     ///
1159     /// Basic usage:
1160     ///
1161     /// ```no_run
1162     /// use std::process::Command;
1163     ///
1164     /// let mut command = Command::new("ls");
1165     /// if let Ok(child) = command.spawn() {
1166     ///     println!("Child's id is {}", child.id());
1167     /// } else {
1168     ///     println!("ls command didn't start");
1169     /// }
1170     /// ```
1171     #[stable(feature = "process_id", since = "1.3.0")]
1172     pub fn id(&self) -> u32 {
1173         self.handle.id()
1174     }
1175
1176     /// Waits for the child to exit completely, returning the status that it
1177     /// exited with. This function will continue to have the same return value
1178     /// after it has been called at least once.
1179     ///
1180     /// The stdin handle to the child process, if any, will be closed
1181     /// before waiting. This helps avoid deadlock: it ensures that the
1182     /// child does not block waiting for input from the parent, while
1183     /// the parent waits for the child to exit.
1184     ///
1185     /// # Examples
1186     ///
1187     /// Basic usage:
1188     ///
1189     /// ```no_run
1190     /// use std::process::Command;
1191     ///
1192     /// let mut command = Command::new("ls");
1193     /// if let Ok(mut child) = command.spawn() {
1194     ///     child.wait().expect("command wasn't running");
1195     ///     println!("Child has finished its execution!");
1196     /// } else {
1197     ///     println!("ls command didn't start");
1198     /// }
1199     /// ```
1200     #[stable(feature = "process", since = "1.0.0")]
1201     pub fn wait(&mut self) -> io::Result<ExitStatus> {
1202         drop(self.stdin.take());
1203         self.handle.wait().map(ExitStatus)
1204     }
1205
1206     /// Attempts to collect the exit status of the child if it has already
1207     /// exited.
1208     ///
1209     /// This function will not block the calling thread and will only advisorily
1210     /// check to see if the child process has exited or not. If the child has
1211     /// exited then on Unix the process id is reaped. This function is
1212     /// guaranteed to repeatedly return a successful exit status so long as the
1213     /// child has already exited.
1214     ///
1215     /// If the child has exited, then `Ok(Some(status))` is returned. If the
1216     /// exit status is not available at this time then `Ok(None)` is returned.
1217     /// If an error occurs, then that error is returned.
1218     ///
1219     /// Note that unlike `wait`, this function will not attempt to drop stdin.
1220     ///
1221     /// # Examples
1222     ///
1223     /// Basic usage:
1224     ///
1225     /// ```no_run
1226     /// use std::process::Command;
1227     ///
1228     /// let mut child = Command::new("ls").spawn().unwrap();
1229     ///
1230     /// match child.try_wait() {
1231     ///     Ok(Some(status)) => println!("exited with: {}", status),
1232     ///     Ok(None) => {
1233     ///         println!("status not ready yet, let's really wait");
1234     ///         let res = child.wait();
1235     ///         println!("result: {:?}", res);
1236     ///     }
1237     ///     Err(e) => println!("error attempting to wait: {}", e),
1238     /// }
1239     /// ```
1240     #[stable(feature = "process_try_wait", since = "1.18.0")]
1241     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1242         Ok(self.handle.try_wait()?.map(ExitStatus))
1243     }
1244
1245     /// Simultaneously waits for the child to exit and collect all remaining
1246     /// output on the stdout/stderr handles, returning an `Output`
1247     /// instance.
1248     ///
1249     /// The stdin handle to the child process, if any, will be closed
1250     /// before waiting. This helps avoid deadlock: it ensures that the
1251     /// child does not block waiting for input from the parent, while
1252     /// the parent waits for the child to exit.
1253     ///
1254     /// By default, stdin, stdout and stderr are inherited from the parent.
1255     /// In order to capture the output into this `Result<Output>` it is
1256     /// necessary to create new pipes between parent and child. Use
1257     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1258     ///
1259     /// # Examples
1260     ///
1261     /// ```should_panic
1262     /// use std::process::{Command, Stdio};
1263     ///
1264     /// let child = Command::new("/bin/cat")
1265     ///     .arg("file.txt")
1266     ///     .stdout(Stdio::piped())
1267     ///     .spawn()
1268     ///     .expect("failed to execute child");
1269     ///
1270     /// let output = child
1271     ///     .wait_with_output()
1272     ///     .expect("failed to wait on child");
1273     ///
1274     /// assert!(output.status.success());
1275     /// ```
1276     ///
1277     #[stable(feature = "process", since = "1.0.0")]
1278     pub fn wait_with_output(mut self) -> io::Result<Output> {
1279         drop(self.stdin.take());
1280
1281         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1282         match (self.stdout.take(), self.stderr.take()) {
1283             (None, None) => {}
1284             (Some(mut out), None) => {
1285                 let res = out.read_to_end(&mut stdout);
1286                 res.unwrap();
1287             }
1288             (None, Some(mut err)) => {
1289                 let res = err.read_to_end(&mut stderr);
1290                 res.unwrap();
1291             }
1292             (Some(out), Some(err)) => {
1293                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1294                 res.unwrap();
1295             }
1296         }
1297
1298         let status = self.wait()?;
1299         Ok(Output {
1300             status,
1301             stdout,
1302             stderr,
1303         })
1304     }
1305 }
1306
1307 /// Terminates the current process with the specified exit code.
1308 ///
1309 /// This function will never return and will immediately terminate the current
1310 /// process. The exit code is passed through to the underlying OS and will be
1311 /// available for consumption by another process.
1312 ///
1313 /// Note that because this function never returns, and that it terminates the
1314 /// process, no destructors on the current stack or any other thread's stack
1315 /// will be run. If a clean shutdown is needed it is recommended to only call
1316 /// this function at a known point where there are no more destructors left
1317 /// to run.
1318 ///
1319 /// ## Platform-specific behavior
1320 ///
1321 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1322 /// will be visible to a parent process inspecting the exit code. On most
1323 /// Unix-like platforms, only the eight least-significant bits are considered.
1324 ///
1325 /// # Examples
1326 ///
1327 /// Due to this function’s behavior regarding destructors, a conventional way
1328 /// to use the function is to extract the actual computation to another
1329 /// function and compute the exit code from its return value:
1330 ///
1331 /// ```
1332 /// fn run_app() -> Result<(), ()> {
1333 ///     // Application logic here
1334 ///     Ok(())
1335 /// }
1336 ///
1337 /// fn main() {
1338 ///     ::std::process::exit(match run_app() {
1339 ///        Ok(_) => 0,
1340 ///        Err(err) => {
1341 ///            eprintln!("error: {:?}", err);
1342 ///            1
1343 ///        }
1344 ///     });
1345 /// }
1346 /// ```
1347 ///
1348 /// Due to [platform-specific behavior], the exit code for this example will be
1349 /// `0` on Linux, but `256` on Windows:
1350 ///
1351 /// ```no_run
1352 /// use std::process;
1353 ///
1354 /// process::exit(0x0100);
1355 /// ```
1356 ///
1357 /// [platform-specific behavior]: #platform-specific-behavior
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn exit(code: i32) -> ! {
1360     ::sys_common::cleanup();
1361     ::sys::os::exit(code)
1362 }
1363
1364 /// Terminates the process in an abnormal fashion.
1365 ///
1366 /// The function will never return and will immediately terminate the current
1367 /// process in a platform specific "abnormal" manner.
1368 ///
1369 /// Note that because this function never returns, and that it terminates the
1370 /// process, no destructors on the current stack or any other thread's stack
1371 /// will be run.
1372 ///
1373 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1374 /// the current thread's stack and calls all destructors.
1375 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1376 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1377 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1378 ///
1379 /// If a clean shutdown is needed it is recommended to only call
1380 /// this function at a known point where there are no more destructors left
1381 /// to run.
1382 ///
1383 /// # Examples
1384 ///
1385 /// ```no_run
1386 /// use std::process;
1387 ///
1388 /// fn main() {
1389 ///     println!("aborting");
1390 ///
1391 ///     process::abort();
1392 ///
1393 ///     // execution never gets here
1394 /// }
1395 /// ```
1396 ///
1397 /// The `abort` function terminates the process, so the destructor will not
1398 /// get run on the example below:
1399 ///
1400 /// ```no_run
1401 /// use std::process;
1402 ///
1403 /// struct HasDrop;
1404 ///
1405 /// impl Drop for HasDrop {
1406 ///     fn drop(&mut self) {
1407 ///         println!("This will never be printed!");
1408 ///     }
1409 /// }
1410 ///
1411 /// fn main() {
1412 ///     let _x = HasDrop;
1413 ///     process::abort();
1414 ///     // the destructor implemented for HasDrop will never get run
1415 /// }
1416 /// ```
1417 ///
1418 /// [`panic!`]: ../../std/macro.panic.html
1419 /// [panic hook]: ../../std/panic/fn.set_hook.html
1420 #[stable(feature = "process_abort", since = "1.17.0")]
1421 pub fn abort() -> ! {
1422     unsafe { ::sys::abort_internal() };
1423 }
1424
1425 /// Returns the OS-assigned process identifier associated with this process.
1426 ///
1427 /// # Examples
1428 ///
1429 /// Basic usage:
1430 ///
1431 /// ```no_run
1432 /// use std::process;
1433 ///
1434 /// println!("My pid is {}", process::id());
1435 /// ```
1436 ///
1437 ///
1438 #[stable(feature = "getpid", since = "1.26.0")]
1439 pub fn id() -> u32 {
1440     ::sys::os::getpid()
1441 }
1442
1443 /// A trait for implementing arbitrary return types in the `main` function.
1444 ///
1445 /// The c-main function only supports to return integers as return type.
1446 /// So, every type implementing the `Termination` trait has to be converted
1447 /// to an integer.
1448 ///
1449 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
1450 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
1451 #[cfg_attr(not(test), lang = "termination")]
1452 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1453 #[rustc_on_unimplemented(
1454   message="`main` has invalid return type `{Self}`",
1455   label="`main` can only return types that implement `{Termination}`")]
1456 pub trait Termination {
1457     /// Is called to get the representation of the value as status code.
1458     /// This status code is returned to the operating system.
1459     fn report(self) -> i32;
1460 }
1461
1462 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1463 impl Termination for () {
1464     #[inline]
1465     fn report(self) -> i32 { ExitCode::SUCCESS.report() }
1466 }
1467
1468 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1469 impl<E: fmt::Debug> Termination for Result<(), E> {
1470     fn report(self) -> i32 {
1471         match self {
1472             Ok(()) => ().report(),
1473             Err(err) => Err::<!, _>(err).report(),
1474         }
1475     }
1476 }
1477
1478 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1479 impl Termination for ! {
1480     fn report(self) -> i32 { self }
1481 }
1482
1483 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1484 impl<E: fmt::Debug> Termination for Result<!, E> {
1485     fn report(self) -> i32 {
1486         let Err(err) = self;
1487         eprintln!("Error: {:?}", err);
1488         ExitCode::FAILURE.report()
1489     }
1490 }
1491
1492 #[unstable(feature = "termination_trait_lib", issue = "43301")]
1493 impl Termination for ExitCode {
1494     #[inline]
1495     fn report(self) -> i32 {
1496         self.0.as_i32()
1497     }
1498 }
1499
1500 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
1501 mod tests {
1502     use io::prelude::*;
1503
1504     use io::ErrorKind;
1505     use str;
1506     use super::{Command, Output, Stdio};
1507
1508     // FIXME(#10380) these tests should not all be ignored on android.
1509
1510     #[test]
1511     #[cfg_attr(target_os = "android", ignore)]
1512     fn smoke() {
1513         let p = if cfg!(target_os = "windows") {
1514             Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1515         } else {
1516             Command::new("true").spawn()
1517         };
1518         assert!(p.is_ok());
1519         let mut p = p.unwrap();
1520         assert!(p.wait().unwrap().success());
1521     }
1522
1523     #[test]
1524     #[cfg_attr(target_os = "android", ignore)]
1525     fn smoke_failure() {
1526         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1527             Ok(..) => panic!(),
1528             Err(..) => {}
1529         }
1530     }
1531
1532     #[test]
1533     #[cfg_attr(target_os = "android", ignore)]
1534     fn exit_reported_right() {
1535         let p = if cfg!(target_os = "windows") {
1536             Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1537         } else {
1538             Command::new("false").spawn()
1539         };
1540         assert!(p.is_ok());
1541         let mut p = p.unwrap();
1542         assert!(p.wait().unwrap().code() == Some(1));
1543         drop(p.wait());
1544     }
1545
1546     #[test]
1547     #[cfg(unix)]
1548     #[cfg_attr(target_os = "android", ignore)]
1549     fn signal_reported_right() {
1550         use os::unix::process::ExitStatusExt;
1551
1552         let mut p = Command::new("/bin/sh")
1553                             .arg("-c").arg("read a")
1554                             .stdin(Stdio::piped())
1555                             .spawn().unwrap();
1556         p.kill().unwrap();
1557         match p.wait().unwrap().signal() {
1558             Some(9) => {},
1559             result => panic!("not terminated by signal 9 (instead, {:?})",
1560                              result),
1561         }
1562     }
1563
1564     pub fn run_output(mut cmd: Command) -> String {
1565         let p = cmd.spawn();
1566         assert!(p.is_ok());
1567         let mut p = p.unwrap();
1568         assert!(p.stdout.is_some());
1569         let mut ret = String::new();
1570         p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1571         assert!(p.wait().unwrap().success());
1572         return ret;
1573     }
1574
1575     #[test]
1576     #[cfg_attr(target_os = "android", ignore)]
1577     fn stdout_works() {
1578         if cfg!(target_os = "windows") {
1579             let mut cmd = Command::new("cmd");
1580             cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1581             assert_eq!(run_output(cmd), "foobar\r\n");
1582         } else {
1583             let mut cmd = Command::new("echo");
1584             cmd.arg("foobar").stdout(Stdio::piped());
1585             assert_eq!(run_output(cmd), "foobar\n");
1586         }
1587     }
1588
1589     #[test]
1590     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1591     fn set_current_dir_works() {
1592         let mut cmd = Command::new("/bin/sh");
1593         cmd.arg("-c").arg("pwd")
1594            .current_dir("/")
1595            .stdout(Stdio::piped());
1596         assert_eq!(run_output(cmd), "/\n");
1597     }
1598
1599     #[test]
1600     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1601     fn stdin_works() {
1602         let mut p = Command::new("/bin/sh")
1603                             .arg("-c").arg("read line; echo $line")
1604                             .stdin(Stdio::piped())
1605                             .stdout(Stdio::piped())
1606                             .spawn().unwrap();
1607         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1608         drop(p.stdin.take());
1609         let mut out = String::new();
1610         p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1611         assert!(p.wait().unwrap().success());
1612         assert_eq!(out, "foobar\n");
1613     }
1614
1615
1616     #[test]
1617     #[cfg_attr(target_os = "android", ignore)]
1618     #[cfg(unix)]
1619     fn uid_works() {
1620         use os::unix::prelude::*;
1621         use libc;
1622         let mut p = Command::new("/bin/sh")
1623                             .arg("-c").arg("true")
1624                             .uid(unsafe { libc::getuid() })
1625                             .gid(unsafe { libc::getgid() })
1626                             .spawn().unwrap();
1627         assert!(p.wait().unwrap().success());
1628     }
1629
1630     #[test]
1631     #[cfg_attr(target_os = "android", ignore)]
1632     #[cfg(unix)]
1633     fn uid_to_root_fails() {
1634         use os::unix::prelude::*;
1635         use libc;
1636
1637         // if we're already root, this isn't a valid test. Most of the bots run
1638         // as non-root though (android is an exception).
1639         if unsafe { libc::getuid() == 0 } { return }
1640         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1641     }
1642
1643     #[test]
1644     #[cfg_attr(target_os = "android", ignore)]
1645     fn test_process_status() {
1646         let mut status = if cfg!(target_os = "windows") {
1647             Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1648         } else {
1649             Command::new("false").status().unwrap()
1650         };
1651         assert!(status.code() == Some(1));
1652
1653         status = if cfg!(target_os = "windows") {
1654             Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1655         } else {
1656             Command::new("true").status().unwrap()
1657         };
1658         assert!(status.success());
1659     }
1660
1661     #[test]
1662     fn test_process_output_fail_to_start() {
1663         match Command::new("/no-binary-by-this-name-should-exist").output() {
1664             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1665             Ok(..) => panic!()
1666         }
1667     }
1668
1669     #[test]
1670     #[cfg_attr(target_os = "android", ignore)]
1671     fn test_process_output_output() {
1672         let Output {status, stdout, stderr}
1673              = if cfg!(target_os = "windows") {
1674                  Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1675              } else {
1676                  Command::new("echo").arg("hello").output().unwrap()
1677              };
1678         let output_str = str::from_utf8(&stdout).unwrap();
1679
1680         assert!(status.success());
1681         assert_eq!(output_str.trim().to_string(), "hello");
1682         assert_eq!(stderr, Vec::new());
1683     }
1684
1685     #[test]
1686     #[cfg_attr(target_os = "android", ignore)]
1687     fn test_process_output_error() {
1688         let Output {status, stdout, stderr}
1689              = if cfg!(target_os = "windows") {
1690                  Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1691              } else {
1692                  Command::new("mkdir").arg("./").output().unwrap()
1693              };
1694
1695         assert!(status.code() == Some(1));
1696         assert_eq!(stdout, Vec::new());
1697         assert!(!stderr.is_empty());
1698     }
1699
1700     #[test]
1701     #[cfg_attr(target_os = "android", ignore)]
1702     fn test_finish_once() {
1703         let mut prog = if cfg!(target_os = "windows") {
1704             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1705         } else {
1706             Command::new("false").spawn().unwrap()
1707         };
1708         assert!(prog.wait().unwrap().code() == Some(1));
1709     }
1710
1711     #[test]
1712     #[cfg_attr(target_os = "android", ignore)]
1713     fn test_finish_twice() {
1714         let mut prog = if cfg!(target_os = "windows") {
1715             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1716         } else {
1717             Command::new("false").spawn().unwrap()
1718         };
1719         assert!(prog.wait().unwrap().code() == Some(1));
1720         assert!(prog.wait().unwrap().code() == Some(1));
1721     }
1722
1723     #[test]
1724     #[cfg_attr(target_os = "android", ignore)]
1725     fn test_wait_with_output_once() {
1726         let prog = if cfg!(target_os = "windows") {
1727             Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1728         } else {
1729             Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1730         };
1731
1732         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1733         let output_str = str::from_utf8(&stdout).unwrap();
1734
1735         assert!(status.success());
1736         assert_eq!(output_str.trim().to_string(), "hello");
1737         assert_eq!(stderr, Vec::new());
1738     }
1739
1740     #[cfg(all(unix, not(target_os="android")))]
1741     pub fn env_cmd() -> Command {
1742         Command::new("env")
1743     }
1744     #[cfg(target_os="android")]
1745     pub fn env_cmd() -> Command {
1746         let mut cmd = Command::new("/system/bin/sh");
1747         cmd.arg("-c").arg("set");
1748         cmd
1749     }
1750
1751     #[cfg(windows)]
1752     pub fn env_cmd() -> Command {
1753         let mut cmd = Command::new("cmd");
1754         cmd.arg("/c").arg("set");
1755         cmd
1756     }
1757
1758     #[test]
1759     fn test_inherit_env() {
1760         use env;
1761
1762         let result = env_cmd().output().unwrap();
1763         let output = String::from_utf8(result.stdout).unwrap();
1764
1765         for (ref k, ref v) in env::vars() {
1766             // Don't check android RANDOM variable which seems to change
1767             // whenever the shell runs, and our `env_cmd` is indeed running a
1768             // shell which means it'll get a different RANDOM than we probably
1769             // have.
1770             //
1771             // Also skip env vars with `-` in the name on android because, well,
1772             // I'm not sure. It appears though that the `set` command above does
1773             // not print env vars with `-` in the name, so we just skip them
1774             // here as we won't find them in the output. Note that most env vars
1775             // use `_` instead of `-`, but our build system sets a few env vars
1776             // with `-` in the name.
1777             if cfg!(target_os = "android") &&
1778                (*k == "RANDOM" || k.contains("-")) {
1779                 continue
1780             }
1781
1782             // Windows has hidden environment variables whose names start with
1783             // equals signs (`=`). Those do not show up in the output of the
1784             // `set` command.
1785             assert!((cfg!(windows) && k.starts_with("=")) ||
1786                     k.starts_with("DYLD") ||
1787                     output.contains(&format!("{}={}", *k, *v)) ||
1788                     output.contains(&format!("{}='{}'", *k, *v)),
1789                     "output doesn't contain `{}={}`\n{}",
1790                     k, v, output);
1791         }
1792     }
1793
1794     #[test]
1795     fn test_override_env() {
1796         use env;
1797
1798         // In some build environments (such as chrooted Nix builds), `env` can
1799         // only be found in the explicitly-provided PATH env variable, not in
1800         // default places such as /bin or /usr/bin. So we need to pass through
1801         // PATH to our sub-process.
1802         let mut cmd = env_cmd();
1803         cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1804         if let Some(p) = env::var_os("PATH") {
1805             cmd.env("PATH", &p);
1806         }
1807         let result = cmd.output().unwrap();
1808         let output = String::from_utf8_lossy(&result.stdout).to_string();
1809
1810         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1811                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1812     }
1813
1814     #[test]
1815     fn test_add_to_env() {
1816         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1817         let output = String::from_utf8_lossy(&result.stdout).to_string();
1818
1819         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1820                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1821     }
1822
1823     #[test]
1824     fn test_capture_env_at_spawn() {
1825         use env;
1826
1827         let mut cmd = env_cmd();
1828         cmd.env("RUN_TEST_NEW_ENV1", "123");
1829
1830         // This variable will not be present if the environment has already
1831         // been captured above.
1832         env::set_var("RUN_TEST_NEW_ENV2", "456");
1833         let result = cmd.output().unwrap();
1834         env::remove_var("RUN_TEST_NEW_ENV2");
1835
1836         let output = String::from_utf8_lossy(&result.stdout).to_string();
1837
1838         assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
1839                 "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
1840         assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
1841                 "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
1842     }
1843
1844     // Regression tests for #30858.
1845     #[test]
1846     fn test_interior_nul_in_progname_is_error() {
1847         match Command::new("has-some-\0\0s-inside").spawn() {
1848             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1849             Ok(_) => panic!(),
1850         }
1851     }
1852
1853     #[test]
1854     fn test_interior_nul_in_arg_is_error() {
1855         match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1856             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1857             Ok(_) => panic!(),
1858         }
1859     }
1860
1861     #[test]
1862     fn test_interior_nul_in_args_is_error() {
1863         match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1864             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1865             Ok(_) => panic!(),
1866         }
1867     }
1868
1869     #[test]
1870     fn test_interior_nul_in_current_dir_is_error() {
1871         match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1872             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1873             Ok(_) => panic!(),
1874         }
1875     }
1876
1877     // Regression tests for #30862.
1878     #[test]
1879     fn test_interior_nul_in_env_key_is_error() {
1880         match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1881             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1882             Ok(_) => panic!(),
1883         }
1884     }
1885
1886     #[test]
1887     fn test_interior_nul_in_env_value_is_error() {
1888         match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1889             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1890             Ok(_) => panic!(),
1891         }
1892     }
1893
1894     /// Test that process creation flags work by debugging a process.
1895     /// Other creation flags make it hard or impossible to detect
1896     /// behavioral changes in the process.
1897     #[test]
1898     #[cfg(windows)]
1899     fn test_creation_flags() {
1900         use os::windows::process::CommandExt;
1901         use sys::c::{BOOL, DWORD, INFINITE};
1902         #[repr(C, packed)]
1903         struct DEBUG_EVENT {
1904             pub event_code: DWORD,
1905             pub process_id: DWORD,
1906             pub thread_id: DWORD,
1907             // This is a union in the real struct, but we don't
1908             // need this data for the purposes of this test.
1909             pub _junk: [u8; 164],
1910         }
1911
1912         extern "system" {
1913             fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1914             fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1915                                   dwContinueStatus: DWORD) -> BOOL;
1916         }
1917
1918         const DEBUG_PROCESS: DWORD = 1;
1919         const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1920         const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1921
1922         let mut child = Command::new("cmd")
1923             .creation_flags(DEBUG_PROCESS)
1924             .stdin(Stdio::piped()).spawn().unwrap();
1925         child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1926         let mut events = 0;
1927         let mut event = DEBUG_EVENT {
1928             event_code: 0,
1929             process_id: 0,
1930             thread_id: 0,
1931             _junk: [0; 164],
1932         };
1933         loop {
1934             if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1935                 panic!("WaitForDebugEvent failed!");
1936             }
1937             events += 1;
1938
1939             if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1940                 break;
1941             }
1942
1943             if unsafe { ContinueDebugEvent(event.process_id,
1944                                            event.thread_id,
1945                                            DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1946                 panic!("ContinueDebugEvent failed!");
1947             }
1948         }
1949         assert!(events > 0);
1950     }
1951
1952     #[test]
1953     fn test_command_implements_send() {
1954         fn take_send_type<T: Send>(_: T) {}
1955         take_send_type(Command::new(""))
1956     }
1957 }