]> git.lizzy.rs Git - rust.git/blob - library/std/src/process.rs
Merge commit 'a5d597637dcb78dc73f93561ce474f23d4177c35' into clippyup
[rust.git] / library / std / src / process.rs
1 //! A module for working with processes.
2 //!
3 //! This module is mostly concerned with spawning and interacting with child
4 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
5 //! current process.
6 //!
7 //! # Spawning a process
8 //!
9 //! The [`Command`] struct is used to configure and spawn processes:
10 //!
11 //! ```no_run
12 //! use std::process::Command;
13 //!
14 //! let output = Command::new("echo")
15 //!                      .arg("Hello world")
16 //!                      .output()
17 //!                      .expect("Failed to execute command");
18 //!
19 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
20 //! ```
21 //!
22 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
23 //! to spawn a process. In particular, [`output`] spawns the child process and
24 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
25 //! that represents the spawned child process.
26 //!
27 //! # Handling I/O
28 //!
29 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
30 //! configured by passing an [`Stdio`] to the corresponding method on
31 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
32 //! example, piping output from one command into another command can be done
33 //! like so:
34 //!
35 //! ```no_run
36 //! use std::process::{Command, Stdio};
37 //!
38 //! // stdout must be configured with `Stdio::piped` in order to use
39 //! // `echo_child.stdout`
40 //! let echo_child = Command::new("echo")
41 //!     .arg("Oh no, a tpyo!")
42 //!     .stdout(Stdio::piped())
43 //!     .spawn()
44 //!     .expect("Failed to start echo process");
45 //!
46 //! // Note that `echo_child` is moved here, but we won't be needing
47 //! // `echo_child` anymore
48 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
49 //!
50 //! let mut sed_child = Command::new("sed")
51 //!     .arg("s/tpyo/typo/")
52 //!     .stdin(Stdio::from(echo_out))
53 //!     .stdout(Stdio::piped())
54 //!     .spawn()
55 //!     .expect("Failed to start sed process");
56 //!
57 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
58 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
59 //! ```
60 //!
61 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
62 //! [`ChildStdin`] implements [`Write`]:
63 //!
64 //! ```no_run
65 //! use std::process::{Command, Stdio};
66 //! use std::io::Write;
67 //!
68 //! let mut child = Command::new("/bin/cat")
69 //!     .stdin(Stdio::piped())
70 //!     .stdout(Stdio::piped())
71 //!     .spawn()
72 //!     .expect("failed to execute child");
73 //!
74 //! // If the child process fills its stdout buffer, it may end up
75 //! // waiting until the parent reads the stdout, and not be able to
76 //! // read stdin in the meantime, causing a deadlock.
77 //! // Writing from another thread ensures that stdout is being read
78 //! // at the same time, avoiding the problem.
79 //! let mut stdin = child.stdin.take().expect("failed to get stdin");
80 //! std::thread::spawn(move || {
81 //!     stdin.write_all(b"test").expect("failed to write to stdin");
82 //! });
83 //!
84 //! let output = child
85 //!     .wait_with_output()
86 //!     .expect("failed to wait on child");
87 //!
88 //! assert_eq!(b"test", output.stdout.as_slice());
89 //! ```
90 //!
91 //! [`spawn`]: Command::spawn
92 //! [`output`]: Command::output
93 //!
94 //! [`stdout`]: Command::stdout
95 //! [`stdin`]: Command::stdin
96 //! [`stderr`]: Command::stderr
97 //!
98 //! [`Write`]: io::Write
99 //! [`Read`]: io::Read
100
101 #![stable(feature = "process", since = "1.0.0")]
102 #![deny(unsafe_op_in_unsafe_fn)]
103
104 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
105 mod tests;
106
107 use crate::io::prelude::*;
108
109 use crate::convert::Infallible;
110 use crate::ffi::OsStr;
111 use crate::fmt;
112 use crate::fs;
113 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
114 use crate::num::NonZeroI32;
115 use crate::path::Path;
116 use crate::str;
117 use crate::sys::pipe::{read2, AnonPipe};
118 use crate::sys::process as imp;
119 #[stable(feature = "command_access", since = "1.57.0")]
120 pub use crate::sys_common::process::CommandEnvs;
121 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
122
123 /// Representation of a running or exited child process.
124 ///
125 /// This structure is used to represent and manage child processes. A child
126 /// process is created via the [`Command`] struct, which configures the
127 /// spawning process and can itself be constructed using a builder-style
128 /// interface.
129 ///
130 /// There is no implementation of [`Drop`] for child processes,
131 /// so if you do not ensure the `Child` has exited then it will continue to
132 /// run, even after the `Child` handle to the child process has gone out of
133 /// scope.
134 ///
135 /// Calling [`wait`] (or other functions that wrap around it) will make
136 /// the parent process wait until the child has actually exited before
137 /// continuing.
138 ///
139 /// # Warning
140 ///
141 /// On some systems, calling [`wait`] or similar is necessary for the OS to
142 /// release resources. A process that terminated but has not been waited on is
143 /// still around as a "zombie". Leaving too many zombies around may exhaust
144 /// global resources (for example process IDs).
145 ///
146 /// The standard library does *not* automatically wait on child processes (not
147 /// even if the `Child` is dropped), it is up to the application developer to do
148 /// so. As a consequence, dropping `Child` handles without waiting on them first
149 /// is not recommended in long-running applications.
150 ///
151 /// # Examples
152 ///
153 /// ```should_panic
154 /// use std::process::Command;
155 ///
156 /// let mut child = Command::new("/bin/cat")
157 ///                         .arg("file.txt")
158 ///                         .spawn()
159 ///                         .expect("failed to execute child");
160 ///
161 /// let ecode = child.wait()
162 ///                  .expect("failed to wait on child");
163 ///
164 /// assert!(ecode.success());
165 /// ```
166 ///
167 /// [`wait`]: Child::wait
168 #[stable(feature = "process", since = "1.0.0")]
169 pub struct Child {
170     pub(crate) handle: imp::Process,
171
172     /// The handle for writing to the child's standard input (stdin), if it has
173     /// been captured. To avoid partially moving
174     /// the `child` and thus blocking yourself from calling
175     /// functions on `child` while using `stdin`,
176     /// you might find it helpful:
177     ///
178     /// ```compile_fail,E0425
179     /// let stdin = child.stdin.take().unwrap();
180     /// ```
181     #[stable(feature = "process", since = "1.0.0")]
182     pub stdin: Option<ChildStdin>,
183
184     /// The handle for reading from the child's standard output (stdout), if it
185     /// has been captured. You might find it helpful to do
186     ///
187     /// ```compile_fail,E0425
188     /// let stdout = child.stdout.take().unwrap();
189     /// ```
190     ///
191     /// to avoid partially moving the `child` and thus blocking yourself from calling
192     /// functions on `child` while using `stdout`.
193     #[stable(feature = "process", since = "1.0.0")]
194     pub stdout: Option<ChildStdout>,
195
196     /// The handle for reading from the child's standard error (stderr), if it
197     /// has been captured. You might find it helpful to do
198     ///
199     /// ```compile_fail,E0425
200     /// let stderr = child.stderr.take().unwrap();
201     /// ```
202     ///
203     /// to avoid partially moving the `child` and thus blocking yourself from calling
204     /// functions on `child` while using `stderr`.
205     #[stable(feature = "process", since = "1.0.0")]
206     pub stderr: Option<ChildStderr>,
207 }
208
209 /// Allows extension traits within `std`.
210 #[unstable(feature = "sealed", issue = "none")]
211 impl crate::sealed::Sealed for Child {}
212
213 impl AsInner<imp::Process> for Child {
214     fn as_inner(&self) -> &imp::Process {
215         &self.handle
216     }
217 }
218
219 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
220     fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
221         Child {
222             handle,
223             stdin: io.stdin.map(ChildStdin::from_inner),
224             stdout: io.stdout.map(ChildStdout::from_inner),
225             stderr: io.stderr.map(ChildStderr::from_inner),
226         }
227     }
228 }
229
230 impl IntoInner<imp::Process> for Child {
231     fn into_inner(self) -> imp::Process {
232         self.handle
233     }
234 }
235
236 #[stable(feature = "std_debug", since = "1.16.0")]
237 impl fmt::Debug for Child {
238     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239         f.debug_struct("Child")
240             .field("stdin", &self.stdin)
241             .field("stdout", &self.stdout)
242             .field("stderr", &self.stderr)
243             .finish_non_exhaustive()
244     }
245 }
246
247 /// A handle to a child process's standard input (stdin).
248 ///
249 /// This struct is used in the [`stdin`] field on [`Child`].
250 ///
251 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
252 /// file handle will be closed. If the child process was blocked on input prior
253 /// to being dropped, it will become unblocked after dropping.
254 ///
255 /// [`stdin`]: Child::stdin
256 /// [dropped]: Drop
257 #[stable(feature = "process", since = "1.0.0")]
258 pub struct ChildStdin {
259     inner: AnonPipe,
260 }
261
262 // In addition to the `impl`s here, `ChildStdin` also has `impl`s for
263 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
264 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
265 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
266 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
267
268 #[stable(feature = "process", since = "1.0.0")]
269 impl Write for ChildStdin {
270     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
271         (&*self).write(buf)
272     }
273
274     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
275         (&*self).write_vectored(bufs)
276     }
277
278     fn is_write_vectored(&self) -> bool {
279         io::Write::is_write_vectored(&&*self)
280     }
281
282     fn flush(&mut self) -> io::Result<()> {
283         (&*self).flush()
284     }
285 }
286
287 #[stable(feature = "write_mt", since = "1.48.0")]
288 impl Write for &ChildStdin {
289     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
290         self.inner.write(buf)
291     }
292
293     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
294         self.inner.write_vectored(bufs)
295     }
296
297     fn is_write_vectored(&self) -> bool {
298         self.inner.is_write_vectored()
299     }
300
301     fn flush(&mut self) -> io::Result<()> {
302         Ok(())
303     }
304 }
305
306 impl AsInner<AnonPipe> for ChildStdin {
307     fn as_inner(&self) -> &AnonPipe {
308         &self.inner
309     }
310 }
311
312 impl IntoInner<AnonPipe> for ChildStdin {
313     fn into_inner(self) -> AnonPipe {
314         self.inner
315     }
316 }
317
318 impl FromInner<AnonPipe> for ChildStdin {
319     fn from_inner(pipe: AnonPipe) -> ChildStdin {
320         ChildStdin { inner: pipe }
321     }
322 }
323
324 #[stable(feature = "std_debug", since = "1.16.0")]
325 impl fmt::Debug for ChildStdin {
326     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327         f.debug_struct("ChildStdin").finish_non_exhaustive()
328     }
329 }
330
331 /// A handle to a child process's standard output (stdout).
332 ///
333 /// This struct is used in the [`stdout`] field on [`Child`].
334 ///
335 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
336 /// underlying file handle will be closed.
337 ///
338 /// [`stdout`]: Child::stdout
339 /// [dropped]: Drop
340 #[stable(feature = "process", since = "1.0.0")]
341 pub struct ChildStdout {
342     inner: AnonPipe,
343 }
344
345 // In addition to the `impl`s here, `ChildStdout` also has `impl`s for
346 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
347 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
348 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
349 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
350
351 #[stable(feature = "process", since = "1.0.0")]
352 impl Read for ChildStdout {
353     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
354         self.inner.read(buf)
355     }
356
357     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
358         self.inner.read_vectored(bufs)
359     }
360
361     #[inline]
362     fn is_read_vectored(&self) -> bool {
363         self.inner.is_read_vectored()
364     }
365
366     #[inline]
367     unsafe fn initializer(&self) -> Initializer {
368         // SAFETY: Read is guaranteed to work on uninitialized memory
369         unsafe { Initializer::nop() }
370     }
371 }
372
373 impl AsInner<AnonPipe> for ChildStdout {
374     fn as_inner(&self) -> &AnonPipe {
375         &self.inner
376     }
377 }
378
379 impl IntoInner<AnonPipe> for ChildStdout {
380     fn into_inner(self) -> AnonPipe {
381         self.inner
382     }
383 }
384
385 impl FromInner<AnonPipe> for ChildStdout {
386     fn from_inner(pipe: AnonPipe) -> ChildStdout {
387         ChildStdout { inner: pipe }
388     }
389 }
390
391 #[stable(feature = "std_debug", since = "1.16.0")]
392 impl fmt::Debug for ChildStdout {
393     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394         f.debug_struct("ChildStdout").finish_non_exhaustive()
395     }
396 }
397
398 /// A handle to a child process's stderr.
399 ///
400 /// This struct is used in the [`stderr`] field on [`Child`].
401 ///
402 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
403 /// underlying file handle will be closed.
404 ///
405 /// [`stderr`]: Child::stderr
406 /// [dropped]: Drop
407 #[stable(feature = "process", since = "1.0.0")]
408 pub struct ChildStderr {
409     inner: AnonPipe,
410 }
411
412 // In addition to the `impl`s here, `ChildStderr` also has `impl`s for
413 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
414 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
415 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
416 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
417
418 #[stable(feature = "process", since = "1.0.0")]
419 impl Read for ChildStderr {
420     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
421         self.inner.read(buf)
422     }
423
424     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
425         self.inner.read_vectored(bufs)
426     }
427
428     #[inline]
429     fn is_read_vectored(&self) -> bool {
430         self.inner.is_read_vectored()
431     }
432
433     #[inline]
434     unsafe fn initializer(&self) -> Initializer {
435         // SAFETY: Read is guaranteed to work on uninitialized memory
436         unsafe { Initializer::nop() }
437     }
438 }
439
440 impl AsInner<AnonPipe> for ChildStderr {
441     fn as_inner(&self) -> &AnonPipe {
442         &self.inner
443     }
444 }
445
446 impl IntoInner<AnonPipe> for ChildStderr {
447     fn into_inner(self) -> AnonPipe {
448         self.inner
449     }
450 }
451
452 impl FromInner<AnonPipe> for ChildStderr {
453     fn from_inner(pipe: AnonPipe) -> ChildStderr {
454         ChildStderr { inner: pipe }
455     }
456 }
457
458 #[stable(feature = "std_debug", since = "1.16.0")]
459 impl fmt::Debug for ChildStderr {
460     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461         f.debug_struct("ChildStderr").finish_non_exhaustive()
462     }
463 }
464
465 /// A process builder, providing fine-grained control
466 /// over how a new process should be spawned.
467 ///
468 /// A default configuration can be
469 /// generated using `Command::new(program)`, where `program` gives a path to the
470 /// program to be executed. Additional builder methods allow the configuration
471 /// to be changed (for example, by adding arguments) prior to spawning:
472 ///
473 /// ```
474 /// use std::process::Command;
475 ///
476 /// let output = if cfg!(target_os = "windows") {
477 ///     Command::new("cmd")
478 ///             .args(["/C", "echo hello"])
479 ///             .output()
480 ///             .expect("failed to execute process")
481 /// } else {
482 ///     Command::new("sh")
483 ///             .arg("-c")
484 ///             .arg("echo hello")
485 ///             .output()
486 ///             .expect("failed to execute process")
487 /// };
488 ///
489 /// let hello = output.stdout;
490 /// ```
491 ///
492 /// `Command` can be reused to spawn multiple processes. The builder methods
493 /// change the command without needing to immediately spawn the process.
494 ///
495 /// ```no_run
496 /// use std::process::Command;
497 ///
498 /// let mut echo_hello = Command::new("sh");
499 /// echo_hello.arg("-c")
500 ///           .arg("echo hello");
501 /// let hello_1 = echo_hello.output().expect("failed to execute process");
502 /// let hello_2 = echo_hello.output().expect("failed to execute process");
503 /// ```
504 ///
505 /// Similarly, you can call builder methods after spawning a process and then
506 /// spawn a new process with the modified settings.
507 ///
508 /// ```no_run
509 /// use std::process::Command;
510 ///
511 /// let mut list_dir = Command::new("ls");
512 ///
513 /// // Execute `ls` in the current directory of the program.
514 /// list_dir.status().expect("process failed to execute");
515 ///
516 /// println!();
517 ///
518 /// // Change `ls` to execute in the root directory.
519 /// list_dir.current_dir("/");
520 ///
521 /// // And then execute `ls` again but in the root directory.
522 /// list_dir.status().expect("process failed to execute");
523 /// ```
524 #[stable(feature = "process", since = "1.0.0")]
525 pub struct Command {
526     inner: imp::Command,
527 }
528
529 /// Allows extension traits within `std`.
530 #[unstable(feature = "sealed", issue = "none")]
531 impl crate::sealed::Sealed for Command {}
532
533 impl Command {
534     /// Constructs a new `Command` for launching the program at
535     /// path `program`, with the following default configuration:
536     ///
537     /// * No arguments to the program
538     /// * Inherit the current process's environment
539     /// * Inherit the current process's working directory
540     /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
541     ///
542     /// Builder methods are provided to change these defaults and
543     /// otherwise configure the process.
544     ///
545     /// If `program` is not an absolute path, the `PATH` will be searched in
546     /// an OS-defined way.
547     ///
548     /// The search path to be used may be controlled by setting the
549     /// `PATH` environment variable on the Command,
550     /// but this has some implementation limitations on Windows
551     /// (see issue #37519).
552     ///
553     /// # Examples
554     ///
555     /// Basic usage:
556     ///
557     /// ```no_run
558     /// use std::process::Command;
559     ///
560     /// Command::new("sh")
561     ///         .spawn()
562     ///         .expect("sh command failed to start");
563     /// ```
564     #[stable(feature = "process", since = "1.0.0")]
565     pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
566         Command { inner: imp::Command::new(program.as_ref()) }
567     }
568
569     /// Adds an argument to pass to the program.
570     ///
571     /// Only one argument can be passed per use. So instead of:
572     ///
573     /// ```no_run
574     /// # std::process::Command::new("sh")
575     /// .arg("-C /path/to/repo")
576     /// # ;
577     /// ```
578     ///
579     /// usage would be:
580     ///
581     /// ```no_run
582     /// # std::process::Command::new("sh")
583     /// .arg("-C")
584     /// .arg("/path/to/repo")
585     /// # ;
586     /// ```
587     ///
588     /// To pass multiple arguments see [`args`].
589     ///
590     /// [`args`]: Command::args
591     ///
592     /// Note that the argument is not passed through a shell, but given
593     /// literally to the program. This means that shell syntax like quotes,
594     /// escaped characters, word splitting, glob patterns, substitution, etc.
595     /// have no effect.
596     ///
597     /// # Examples
598     ///
599     /// Basic usage:
600     ///
601     /// ```no_run
602     /// use std::process::Command;
603     ///
604     /// Command::new("ls")
605     ///         .arg("-l")
606     ///         .arg("-a")
607     ///         .spawn()
608     ///         .expect("ls command failed to start");
609     /// ```
610     #[stable(feature = "process", since = "1.0.0")]
611     pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
612         self.inner.arg(arg.as_ref());
613         self
614     }
615
616     /// Adds multiple arguments to pass to the program.
617     ///
618     /// To pass a single argument see [`arg`].
619     ///
620     /// [`arg`]: Command::arg
621     ///
622     /// Note that the arguments are not passed through a shell, but given
623     /// literally to the program. This means that shell syntax like quotes,
624     /// escaped characters, word splitting, glob patterns, substitution, etc.
625     /// have no effect.
626     ///
627     /// # Examples
628     ///
629     /// Basic usage:
630     ///
631     /// ```no_run
632     /// use std::process::Command;
633     ///
634     /// Command::new("ls")
635     ///         .args(["-l", "-a"])
636     ///         .spawn()
637     ///         .expect("ls command failed to start");
638     /// ```
639     #[stable(feature = "process", since = "1.0.0")]
640     pub fn args<I, S>(&mut self, args: I) -> &mut Command
641     where
642         I: IntoIterator<Item = S>,
643         S: AsRef<OsStr>,
644     {
645         for arg in args {
646             self.arg(arg.as_ref());
647         }
648         self
649     }
650
651     /// Inserts or updates an environment variable mapping.
652     ///
653     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
654     /// and case-sensitive on all other platforms.
655     ///
656     /// # Examples
657     ///
658     /// Basic usage:
659     ///
660     /// ```no_run
661     /// use std::process::Command;
662     ///
663     /// Command::new("ls")
664     ///         .env("PATH", "/bin")
665     ///         .spawn()
666     ///         .expect("ls command failed to start");
667     /// ```
668     #[stable(feature = "process", since = "1.0.0")]
669     pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
670     where
671         K: AsRef<OsStr>,
672         V: AsRef<OsStr>,
673     {
674         self.inner.env_mut().set(key.as_ref(), val.as_ref());
675         self
676     }
677
678     /// Adds or updates multiple environment variable mappings.
679     ///
680     /// # Examples
681     ///
682     /// Basic usage:
683     ///
684     /// ```no_run
685     /// use std::process::{Command, Stdio};
686     /// use std::env;
687     /// use std::collections::HashMap;
688     ///
689     /// let filtered_env : HashMap<String, String> =
690     ///     env::vars().filter(|&(ref k, _)|
691     ///         k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
692     ///     ).collect();
693     ///
694     /// Command::new("printenv")
695     ///         .stdin(Stdio::null())
696     ///         .stdout(Stdio::inherit())
697     ///         .env_clear()
698     ///         .envs(&filtered_env)
699     ///         .spawn()
700     ///         .expect("printenv failed to start");
701     /// ```
702     #[stable(feature = "command_envs", since = "1.19.0")]
703     pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
704     where
705         I: IntoIterator<Item = (K, V)>,
706         K: AsRef<OsStr>,
707         V: AsRef<OsStr>,
708     {
709         for (ref key, ref val) in vars {
710             self.inner.env_mut().set(key.as_ref(), val.as_ref());
711         }
712         self
713     }
714
715     /// Removes an environment variable mapping.
716     ///
717     /// # Examples
718     ///
719     /// Basic usage:
720     ///
721     /// ```no_run
722     /// use std::process::Command;
723     ///
724     /// Command::new("ls")
725     ///         .env_remove("PATH")
726     ///         .spawn()
727     ///         .expect("ls command failed to start");
728     /// ```
729     #[stable(feature = "process", since = "1.0.0")]
730     pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
731         self.inner.env_mut().remove(key.as_ref());
732         self
733     }
734
735     /// Clears the entire environment map for the child process.
736     ///
737     /// # Examples
738     ///
739     /// Basic usage:
740     ///
741     /// ```no_run
742     /// use std::process::Command;
743     ///
744     /// Command::new("ls")
745     ///         .env_clear()
746     ///         .spawn()
747     ///         .expect("ls command failed to start");
748     /// ```
749     #[stable(feature = "process", since = "1.0.0")]
750     pub fn env_clear(&mut self) -> &mut Command {
751         self.inner.env_mut().clear();
752         self
753     }
754
755     /// Sets the working directory for the child process.
756     ///
757     /// # Platform-specific behavior
758     ///
759     /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
760     /// whether it should be interpreted relative to the parent's working
761     /// directory or relative to `current_dir`. The behavior in this case is
762     /// platform specific and unstable, and it's recommended to use
763     /// [`canonicalize`] to get an absolute program path instead.
764     ///
765     /// # Examples
766     ///
767     /// Basic usage:
768     ///
769     /// ```no_run
770     /// use std::process::Command;
771     ///
772     /// Command::new("ls")
773     ///         .current_dir("/bin")
774     ///         .spawn()
775     ///         .expect("ls command failed to start");
776     /// ```
777     ///
778     /// [`canonicalize`]: crate::fs::canonicalize
779     #[stable(feature = "process", since = "1.0.0")]
780     pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
781         self.inner.cwd(dir.as_ref().as_ref());
782         self
783     }
784
785     /// Configuration for the child process's standard input (stdin) handle.
786     ///
787     /// Defaults to [`inherit`] when used with `spawn` or `status`, and
788     /// defaults to [`piped`] when used with `output`.
789     ///
790     /// [`inherit`]: Stdio::inherit
791     /// [`piped`]: Stdio::piped
792     ///
793     /// # Examples
794     ///
795     /// Basic usage:
796     ///
797     /// ```no_run
798     /// use std::process::{Command, Stdio};
799     ///
800     /// Command::new("ls")
801     ///         .stdin(Stdio::null())
802     ///         .spawn()
803     ///         .expect("ls command failed to start");
804     /// ```
805     #[stable(feature = "process", since = "1.0.0")]
806     pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
807         self.inner.stdin(cfg.into().0);
808         self
809     }
810
811     /// Configuration for the child process's standard output (stdout) handle.
812     ///
813     /// Defaults to [`inherit`] when used with `spawn` or `status`, and
814     /// defaults to [`piped`] when used with `output`.
815     ///
816     /// [`inherit`]: Stdio::inherit
817     /// [`piped`]: Stdio::piped
818     ///
819     /// # Examples
820     ///
821     /// Basic usage:
822     ///
823     /// ```no_run
824     /// use std::process::{Command, Stdio};
825     ///
826     /// Command::new("ls")
827     ///         .stdout(Stdio::null())
828     ///         .spawn()
829     ///         .expect("ls command failed to start");
830     /// ```
831     #[stable(feature = "process", since = "1.0.0")]
832     pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
833         self.inner.stdout(cfg.into().0);
834         self
835     }
836
837     /// Configuration for the child process's standard error (stderr) handle.
838     ///
839     /// Defaults to [`inherit`] when used with `spawn` or `status`, and
840     /// defaults to [`piped`] when used with `output`.
841     ///
842     /// [`inherit`]: Stdio::inherit
843     /// [`piped`]: Stdio::piped
844     ///
845     /// # Examples
846     ///
847     /// Basic usage:
848     ///
849     /// ```no_run
850     /// use std::process::{Command, Stdio};
851     ///
852     /// Command::new("ls")
853     ///         .stderr(Stdio::null())
854     ///         .spawn()
855     ///         .expect("ls command failed to start");
856     /// ```
857     #[stable(feature = "process", since = "1.0.0")]
858     pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
859         self.inner.stderr(cfg.into().0);
860         self
861     }
862
863     /// Executes the command as a child process, returning a handle to it.
864     ///
865     /// By default, stdin, stdout and stderr are inherited from the parent.
866     ///
867     /// # Examples
868     ///
869     /// Basic usage:
870     ///
871     /// ```no_run
872     /// use std::process::Command;
873     ///
874     /// Command::new("ls")
875     ///         .spawn()
876     ///         .expect("ls command failed to start");
877     /// ```
878     #[stable(feature = "process", since = "1.0.0")]
879     pub fn spawn(&mut self) -> io::Result<Child> {
880         self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
881     }
882
883     /// Executes the command as a child process, waiting for it to finish and
884     /// collecting all of its output.
885     ///
886     /// By default, stdout and stderr are captured (and used to provide the
887     /// resulting output). Stdin is not inherited from the parent and any
888     /// attempt by the child process to read from the stdin stream will result
889     /// in the stream immediately closing.
890     ///
891     /// # Examples
892     ///
893     /// ```should_panic
894     /// use std::process::Command;
895     /// use std::io::{self, Write};
896     /// let output = Command::new("/bin/cat")
897     ///                      .arg("file.txt")
898     ///                      .output()
899     ///                      .expect("failed to execute process");
900     ///
901     /// println!("status: {}", output.status);
902     /// io::stdout().write_all(&output.stdout).unwrap();
903     /// io::stderr().write_all(&output.stderr).unwrap();
904     ///
905     /// assert!(output.status.success());
906     /// ```
907     #[stable(feature = "process", since = "1.0.0")]
908     pub fn output(&mut self) -> io::Result<Output> {
909         self.inner
910             .spawn(imp::Stdio::MakePipe, false)
911             .map(Child::from_inner)
912             .and_then(|p| p.wait_with_output())
913     }
914
915     /// Executes a command as a child process, waiting for it to finish and
916     /// collecting its status.
917     ///
918     /// By default, stdin, stdout and stderr are inherited from the parent.
919     ///
920     /// # Examples
921     ///
922     /// ```should_panic
923     /// use std::process::Command;
924     ///
925     /// let status = Command::new("/bin/cat")
926     ///                      .arg("file.txt")
927     ///                      .status()
928     ///                      .expect("failed to execute process");
929     ///
930     /// println!("process finished with: {}", status);
931     ///
932     /// assert!(status.success());
933     /// ```
934     #[stable(feature = "process", since = "1.0.0")]
935     pub fn status(&mut self) -> io::Result<ExitStatus> {
936         self.inner
937             .spawn(imp::Stdio::Inherit, true)
938             .map(Child::from_inner)
939             .and_then(|mut p| p.wait())
940     }
941
942     /// Returns the path to the program that was given to [`Command::new`].
943     ///
944     /// # Examples
945     ///
946     /// ```
947     /// use std::process::Command;
948     ///
949     /// let cmd = Command::new("echo");
950     /// assert_eq!(cmd.get_program(), "echo");
951     /// ```
952     #[must_use]
953     #[stable(feature = "command_access", since = "1.57.0")]
954     pub fn get_program(&self) -> &OsStr {
955         self.inner.get_program()
956     }
957
958     /// Returns an iterator of the arguments that will be passed to the program.
959     ///
960     /// This does not include the path to the program as the first argument;
961     /// it only includes the arguments specified with [`Command::arg`] and
962     /// [`Command::args`].
963     ///
964     /// # Examples
965     ///
966     /// ```
967     /// use std::ffi::OsStr;
968     /// use std::process::Command;
969     ///
970     /// let mut cmd = Command::new("echo");
971     /// cmd.arg("first").arg("second");
972     /// let args: Vec<&OsStr> = cmd.get_args().collect();
973     /// assert_eq!(args, &["first", "second"]);
974     /// ```
975     #[stable(feature = "command_access", since = "1.57.0")]
976     pub fn get_args(&self) -> CommandArgs<'_> {
977         CommandArgs { inner: self.inner.get_args() }
978     }
979
980     /// Returns an iterator of the environment variables that will be set when
981     /// the process is spawned.
982     ///
983     /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
984     /// value is the key, and the second is the value, which is [`None`] if
985     /// the environment variable is to be explicitly removed.
986     ///
987     /// This only includes environment variables explicitly set with
988     /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
989     /// does not include environment variables that will be inherited by the
990     /// child process.
991     ///
992     /// # Examples
993     ///
994     /// ```
995     /// use std::ffi::OsStr;
996     /// use std::process::Command;
997     ///
998     /// let mut cmd = Command::new("ls");
999     /// cmd.env("TERM", "dumb").env_remove("TZ");
1000     /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1001     /// assert_eq!(envs, &[
1002     ///     (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1003     ///     (OsStr::new("TZ"), None)
1004     /// ]);
1005     /// ```
1006     #[stable(feature = "command_access", since = "1.57.0")]
1007     pub fn get_envs(&self) -> CommandEnvs<'_> {
1008         self.inner.get_envs()
1009     }
1010
1011     /// Returns the working directory for the child process.
1012     ///
1013     /// This returns [`None`] if the working directory will not be changed.
1014     ///
1015     /// # Examples
1016     ///
1017     /// ```
1018     /// use std::path::Path;
1019     /// use std::process::Command;
1020     ///
1021     /// let mut cmd = Command::new("ls");
1022     /// assert_eq!(cmd.get_current_dir(), None);
1023     /// cmd.current_dir("/bin");
1024     /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1025     /// ```
1026     #[must_use]
1027     #[stable(feature = "command_access", since = "1.57.0")]
1028     pub fn get_current_dir(&self) -> Option<&Path> {
1029         self.inner.get_current_dir()
1030     }
1031 }
1032
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl fmt::Debug for Command {
1035     /// Format the program and arguments of a Command for display. Any
1036     /// non-utf8 data is lossily converted using the utf8 replacement
1037     /// character.
1038     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1039         self.inner.fmt(f)
1040     }
1041 }
1042
1043 impl AsInner<imp::Command> for Command {
1044     fn as_inner(&self) -> &imp::Command {
1045         &self.inner
1046     }
1047 }
1048
1049 impl AsInnerMut<imp::Command> for Command {
1050     fn as_inner_mut(&mut self) -> &mut imp::Command {
1051         &mut self.inner
1052     }
1053 }
1054
1055 /// An iterator over the command arguments.
1056 ///
1057 /// This struct is created by [`Command::get_args`]. See its documentation for
1058 /// more.
1059 #[must_use = "iterators are lazy and do nothing unless consumed"]
1060 #[stable(feature = "command_access", since = "1.57.0")]
1061 #[derive(Debug)]
1062 pub struct CommandArgs<'a> {
1063     inner: imp::CommandArgs<'a>,
1064 }
1065
1066 #[stable(feature = "command_access", since = "1.57.0")]
1067 impl<'a> Iterator for CommandArgs<'a> {
1068     type Item = &'a OsStr;
1069     fn next(&mut self) -> Option<&'a OsStr> {
1070         self.inner.next()
1071     }
1072     fn size_hint(&self) -> (usize, Option<usize>) {
1073         self.inner.size_hint()
1074     }
1075 }
1076
1077 #[stable(feature = "command_access", since = "1.57.0")]
1078 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1079     fn len(&self) -> usize {
1080         self.inner.len()
1081     }
1082     fn is_empty(&self) -> bool {
1083         self.inner.is_empty()
1084     }
1085 }
1086
1087 /// The output of a finished process.
1088 ///
1089 /// This is returned in a Result by either the [`output`] method of a
1090 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1091 /// process.
1092 ///
1093 /// [`output`]: Command::output
1094 /// [`wait_with_output`]: Child::wait_with_output
1095 #[derive(PartialEq, Eq, Clone)]
1096 #[stable(feature = "process", since = "1.0.0")]
1097 pub struct Output {
1098     /// The status (exit code) of the process.
1099     #[stable(feature = "process", since = "1.0.0")]
1100     pub status: ExitStatus,
1101     /// The data that the process wrote to stdout.
1102     #[stable(feature = "process", since = "1.0.0")]
1103     pub stdout: Vec<u8>,
1104     /// The data that the process wrote to stderr.
1105     #[stable(feature = "process", since = "1.0.0")]
1106     pub stderr: Vec<u8>,
1107 }
1108
1109 // If either stderr or stdout are valid utf8 strings it prints the valid
1110 // strings, otherwise it prints the byte sequence instead
1111 #[stable(feature = "process_output_debug", since = "1.7.0")]
1112 impl fmt::Debug for Output {
1113     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1114         let stdout_utf8 = str::from_utf8(&self.stdout);
1115         let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1116             Ok(ref str) => str,
1117             Err(_) => &self.stdout,
1118         };
1119
1120         let stderr_utf8 = str::from_utf8(&self.stderr);
1121         let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1122             Ok(ref str) => str,
1123             Err(_) => &self.stderr,
1124         };
1125
1126         fmt.debug_struct("Output")
1127             .field("status", &self.status)
1128             .field("stdout", stdout_debug)
1129             .field("stderr", stderr_debug)
1130             .finish()
1131     }
1132 }
1133
1134 /// Describes what to do with a standard I/O stream for a child process when
1135 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1136 ///
1137 /// [`stdin`]: Command::stdin
1138 /// [`stdout`]: Command::stdout
1139 /// [`stderr`]: Command::stderr
1140 #[stable(feature = "process", since = "1.0.0")]
1141 pub struct Stdio(imp::Stdio);
1142
1143 impl Stdio {
1144     /// A new pipe should be arranged to connect the parent and child processes.
1145     ///
1146     /// # Examples
1147     ///
1148     /// With stdout:
1149     ///
1150     /// ```no_run
1151     /// use std::process::{Command, Stdio};
1152     ///
1153     /// let output = Command::new("echo")
1154     ///     .arg("Hello, world!")
1155     ///     .stdout(Stdio::piped())
1156     ///     .output()
1157     ///     .expect("Failed to execute command");
1158     ///
1159     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1160     /// // Nothing echoed to console
1161     /// ```
1162     ///
1163     /// With stdin:
1164     ///
1165     /// ```no_run
1166     /// use std::io::Write;
1167     /// use std::process::{Command, Stdio};
1168     ///
1169     /// let mut child = Command::new("rev")
1170     ///     .stdin(Stdio::piped())
1171     ///     .stdout(Stdio::piped())
1172     ///     .spawn()
1173     ///     .expect("Failed to spawn child process");
1174     ///
1175     /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1176     /// std::thread::spawn(move || {
1177     ///     stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1178     /// });
1179     ///
1180     /// let output = child.wait_with_output().expect("Failed to read stdout");
1181     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1182     /// ```
1183     ///
1184     /// Writing more than a pipe buffer's worth of input to stdin without also reading
1185     /// stdout and stderr at the same time may cause a deadlock.
1186     /// This is an issue when running any program that doesn't guarantee that it reads
1187     /// its entire stdin before writing more than a pipe buffer's worth of output.
1188     /// The size of a pipe buffer varies on different targets.
1189     ///
1190     #[must_use]
1191     #[stable(feature = "process", since = "1.0.0")]
1192     pub fn piped() -> Stdio {
1193         Stdio(imp::Stdio::MakePipe)
1194     }
1195
1196     /// The child inherits from the corresponding parent descriptor.
1197     ///
1198     /// # Examples
1199     ///
1200     /// With stdout:
1201     ///
1202     /// ```no_run
1203     /// use std::process::{Command, Stdio};
1204     ///
1205     /// let output = Command::new("echo")
1206     ///     .arg("Hello, world!")
1207     ///     .stdout(Stdio::inherit())
1208     ///     .output()
1209     ///     .expect("Failed to execute command");
1210     ///
1211     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1212     /// // "Hello, world!" echoed to console
1213     /// ```
1214     ///
1215     /// With stdin:
1216     ///
1217     /// ```no_run
1218     /// use std::process::{Command, Stdio};
1219     /// use std::io::{self, Write};
1220     ///
1221     /// let output = Command::new("rev")
1222     ///     .stdin(Stdio::inherit())
1223     ///     .stdout(Stdio::piped())
1224     ///     .output()
1225     ///     .expect("Failed to execute command");
1226     ///
1227     /// print!("You piped in the reverse of: ");
1228     /// io::stdout().write_all(&output.stdout).unwrap();
1229     /// ```
1230     #[must_use]
1231     #[stable(feature = "process", since = "1.0.0")]
1232     pub fn inherit() -> Stdio {
1233         Stdio(imp::Stdio::Inherit)
1234     }
1235
1236     /// This stream will be ignored. This is the equivalent of attaching the
1237     /// stream to `/dev/null`.
1238     ///
1239     /// # Examples
1240     ///
1241     /// With stdout:
1242     ///
1243     /// ```no_run
1244     /// use std::process::{Command, Stdio};
1245     ///
1246     /// let output = Command::new("echo")
1247     ///     .arg("Hello, world!")
1248     ///     .stdout(Stdio::null())
1249     ///     .output()
1250     ///     .expect("Failed to execute command");
1251     ///
1252     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1253     /// // Nothing echoed to console
1254     /// ```
1255     ///
1256     /// With stdin:
1257     ///
1258     /// ```no_run
1259     /// use std::process::{Command, Stdio};
1260     ///
1261     /// let output = Command::new("rev")
1262     ///     .stdin(Stdio::null())
1263     ///     .stdout(Stdio::piped())
1264     ///     .output()
1265     ///     .expect("Failed to execute command");
1266     ///
1267     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1268     /// // Ignores any piped-in input
1269     /// ```
1270     #[must_use]
1271     #[stable(feature = "process", since = "1.0.0")]
1272     pub fn null() -> Stdio {
1273         Stdio(imp::Stdio::Null)
1274     }
1275 }
1276
1277 impl FromInner<imp::Stdio> for Stdio {
1278     fn from_inner(inner: imp::Stdio) -> Stdio {
1279         Stdio(inner)
1280     }
1281 }
1282
1283 #[stable(feature = "std_debug", since = "1.16.0")]
1284 impl fmt::Debug for Stdio {
1285     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1286         f.debug_struct("Stdio").finish_non_exhaustive()
1287     }
1288 }
1289
1290 #[stable(feature = "stdio_from", since = "1.20.0")]
1291 impl From<ChildStdin> for Stdio {
1292     /// Converts a `ChildStdin` into a `Stdio`
1293     ///
1294     /// # Examples
1295     ///
1296     /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1297     ///
1298     /// ```rust,no_run
1299     /// use std::process::{Command, Stdio};
1300     ///
1301     /// let reverse = Command::new("rev")
1302     ///     .stdin(Stdio::piped())
1303     ///     .spawn()
1304     ///     .expect("failed reverse command");
1305     ///
1306     /// let _echo = Command::new("echo")
1307     ///     .arg("Hello, world!")
1308     ///     .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1309     ///     .output()
1310     ///     .expect("failed echo command");
1311     ///
1312     /// // "!dlrow ,olleH" echoed to console
1313     /// ```
1314     fn from(child: ChildStdin) -> Stdio {
1315         Stdio::from_inner(child.into_inner().into())
1316     }
1317 }
1318
1319 #[stable(feature = "stdio_from", since = "1.20.0")]
1320 impl From<ChildStdout> for Stdio {
1321     /// Converts a `ChildStdout` into a `Stdio`
1322     ///
1323     /// # Examples
1324     ///
1325     /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1326     ///
1327     /// ```rust,no_run
1328     /// use std::process::{Command, Stdio};
1329     ///
1330     /// let hello = Command::new("echo")
1331     ///     .arg("Hello, world!")
1332     ///     .stdout(Stdio::piped())
1333     ///     .spawn()
1334     ///     .expect("failed echo command");
1335     ///
1336     /// let reverse = Command::new("rev")
1337     ///     .stdin(hello.stdout.unwrap())  // Converted into a Stdio here
1338     ///     .output()
1339     ///     .expect("failed reverse command");
1340     ///
1341     /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1342     /// ```
1343     fn from(child: ChildStdout) -> Stdio {
1344         Stdio::from_inner(child.into_inner().into())
1345     }
1346 }
1347
1348 #[stable(feature = "stdio_from", since = "1.20.0")]
1349 impl From<ChildStderr> for Stdio {
1350     /// Converts a `ChildStderr` into a `Stdio`
1351     ///
1352     /// # Examples
1353     ///
1354     /// ```rust,no_run
1355     /// use std::process::{Command, Stdio};
1356     ///
1357     /// let reverse = Command::new("rev")
1358     ///     .arg("non_existing_file.txt")
1359     ///     .stderr(Stdio::piped())
1360     ///     .spawn()
1361     ///     .expect("failed reverse command");
1362     ///
1363     /// let cat = Command::new("cat")
1364     ///     .arg("-")
1365     ///     .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1366     ///     .output()
1367     ///     .expect("failed echo command");
1368     ///
1369     /// assert_eq!(
1370     ///     String::from_utf8_lossy(&cat.stdout),
1371     ///     "rev: cannot open non_existing_file.txt: No such file or directory\n"
1372     /// );
1373     /// ```
1374     fn from(child: ChildStderr) -> Stdio {
1375         Stdio::from_inner(child.into_inner().into())
1376     }
1377 }
1378
1379 #[stable(feature = "stdio_from", since = "1.20.0")]
1380 impl From<fs::File> for Stdio {
1381     /// Converts a `File` into a `Stdio`
1382     ///
1383     /// # Examples
1384     ///
1385     /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1386     ///
1387     /// ```rust,no_run
1388     /// use std::fs::File;
1389     /// use std::process::Command;
1390     ///
1391     /// // With the `foo.txt` file containing `Hello, world!"
1392     /// let file = File::open("foo.txt").unwrap();
1393     ///
1394     /// let reverse = Command::new("rev")
1395     ///     .stdin(file)  // Implicit File conversion into a Stdio
1396     ///     .output()
1397     ///     .expect("failed reverse command");
1398     ///
1399     /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1400     /// ```
1401     fn from(file: fs::File) -> Stdio {
1402         Stdio::from_inner(file.into_inner().into())
1403     }
1404 }
1405
1406 /// Describes the result of a process after it has terminated.
1407 ///
1408 /// This `struct` is used to represent the exit status or other termination of a child process.
1409 /// Child processes are created via the [`Command`] struct and their exit
1410 /// status is exposed through the [`status`] method, or the [`wait`] method
1411 /// of a [`Child`] process.
1412 ///
1413 /// An `ExitStatus` represents every possible disposition of a process.  On Unix this
1414 /// is the **wait status**.  It is *not* simply an *exit status* (a value passed to `exit`).
1415 ///
1416 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1417 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1418 ///
1419 /// [`status`]: Command::status
1420 /// [`wait`]: Child::wait
1421 //
1422 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1423 // vs `_exit`.  Naming of Unix system calls is not standardised across Unices, so terminology is a
1424 // matter of convention and tradition.  For clarity we usually speak of `exit`, even when we might
1425 // mean an underlying system call such as `_exit`.
1426 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1427 #[stable(feature = "process", since = "1.0.0")]
1428 pub struct ExitStatus(imp::ExitStatus);
1429
1430 /// Allows extension traits within `std`.
1431 #[unstable(feature = "sealed", issue = "none")]
1432 impl crate::sealed::Sealed for ExitStatus {}
1433
1434 impl ExitStatus {
1435     /// Was termination successful?  Returns a `Result`.
1436     ///
1437     /// # Examples
1438     ///
1439     /// ```
1440     /// #![feature(exit_status_error)]
1441     /// # if cfg!(unix) {
1442     /// use std::process::Command;
1443     ///
1444     /// let status = Command::new("ls")
1445     ///                      .arg("/dev/nonexistent")
1446     ///                      .status()
1447     ///                      .expect("ls could not be executed");
1448     ///
1449     /// println!("ls: {}", status);
1450     /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1451     /// # } // cfg!(unix)
1452     /// ```
1453     #[unstable(feature = "exit_status_error", issue = "84908")]
1454     pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1455         self.0.exit_ok().map_err(ExitStatusError)
1456     }
1457
1458     /// Was termination successful? Signal termination is not considered a
1459     /// success, and success is defined as a zero exit status.
1460     ///
1461     /// # Examples
1462     ///
1463     /// ```rust,no_run
1464     /// use std::process::Command;
1465     ///
1466     /// let status = Command::new("mkdir")
1467     ///                      .arg("projects")
1468     ///                      .status()
1469     ///                      .expect("failed to execute mkdir");
1470     ///
1471     /// if status.success() {
1472     ///     println!("'projects/' directory created");
1473     /// } else {
1474     ///     println!("failed to create 'projects/' directory: {}", status);
1475     /// }
1476     /// ```
1477     #[must_use]
1478     #[stable(feature = "process", since = "1.0.0")]
1479     pub fn success(&self) -> bool {
1480         self.0.exit_ok().is_ok()
1481     }
1482
1483     /// Returns the exit code of the process, if any.
1484     ///
1485     /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1486     /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1487     /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1488     /// runtime system (often, for example, 255, 254, 127 or 126).
1489     ///
1490     /// On Unix, this will return `None` if the process was terminated by a signal.
1491     /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1492     /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1493     ///
1494     /// # Examples
1495     ///
1496     /// ```no_run
1497     /// use std::process::Command;
1498     ///
1499     /// let status = Command::new("mkdir")
1500     ///                      .arg("projects")
1501     ///                      .status()
1502     ///                      .expect("failed to execute mkdir");
1503     ///
1504     /// match status.code() {
1505     ///     Some(code) => println!("Exited with status code: {}", code),
1506     ///     None       => println!("Process terminated by signal")
1507     /// }
1508     /// ```
1509     #[must_use]
1510     #[stable(feature = "process", since = "1.0.0")]
1511     pub fn code(&self) -> Option<i32> {
1512         self.0.code()
1513     }
1514 }
1515
1516 impl AsInner<imp::ExitStatus> for ExitStatus {
1517     fn as_inner(&self) -> &imp::ExitStatus {
1518         &self.0
1519     }
1520 }
1521
1522 impl FromInner<imp::ExitStatus> for ExitStatus {
1523     fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1524         ExitStatus(s)
1525     }
1526 }
1527
1528 #[stable(feature = "process", since = "1.0.0")]
1529 impl fmt::Display for ExitStatus {
1530     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531         self.0.fmt(f)
1532     }
1533 }
1534
1535 /// Allows extension traits within `std`.
1536 #[unstable(feature = "sealed", issue = "none")]
1537 impl crate::sealed::Sealed for ExitStatusError {}
1538
1539 /// Describes the result of a process after it has failed
1540 ///
1541 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1542 ///
1543 /// # Examples
1544 ///
1545 /// ```
1546 /// #![feature(exit_status_error)]
1547 /// # if cfg!(unix) {
1548 /// use std::process::{Command, ExitStatusError};
1549 ///
1550 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1551 ///     Command::new(cmd).status().unwrap().exit_ok()?;
1552 ///     Ok(())
1553 /// }
1554 ///
1555 /// run("true").unwrap();
1556 /// run("false").unwrap_err();
1557 /// # } // cfg!(unix)
1558 /// ```
1559 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1560 #[unstable(feature = "exit_status_error", issue = "84908")]
1561 // The definition of imp::ExitStatusError should ideally be such that
1562 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1563 pub struct ExitStatusError(imp::ExitStatusError);
1564
1565 #[unstable(feature = "exit_status_error", issue = "84908")]
1566 impl ExitStatusError {
1567     /// Reports the exit code, if applicable, from an `ExitStatusError`.
1568     ///
1569     /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1570     /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1571     /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1572     /// runtime system (often, for example, 255, 254, 127 or 126).
1573     ///
1574     /// On Unix, this will return `None` if the process was terminated by a signal.  If you want to
1575     /// handle such situations specially, consider using methods from
1576     /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1577     ///
1578     /// If the process finished by calling `exit` with a nonzero value, this will return
1579     /// that exit status.
1580     ///
1581     /// If the error was something else, it will return `None`.
1582     ///
1583     /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1584     /// `ExitStatusError`.  So the return value from `ExitStatusError::code()` is always nonzero.
1585     ///
1586     /// # Examples
1587     ///
1588     /// ```
1589     /// #![feature(exit_status_error)]
1590     /// # #[cfg(unix)] {
1591     /// use std::process::Command;
1592     ///
1593     /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1594     /// assert_eq!(bad.code(), Some(1));
1595     /// # } // #[cfg(unix)]
1596     /// ```
1597     #[must_use]
1598     pub fn code(&self) -> Option<i32> {
1599         self.code_nonzero().map(Into::into)
1600     }
1601
1602     /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1603     ///
1604     /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1605     ///
1606     /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1607     /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1608     /// a type-level guarantee of nonzeroness.
1609     ///
1610     /// # Examples
1611     ///
1612     /// ```
1613     /// #![feature(exit_status_error)]
1614     /// # if cfg!(unix) {
1615     /// use std::convert::TryFrom;
1616     /// use std::num::NonZeroI32;
1617     /// use std::process::Command;
1618     ///
1619     /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1620     /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1621     /// # } // cfg!(unix)
1622     /// ```
1623     #[must_use]
1624     pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1625         self.0.code()
1626     }
1627
1628     /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1629     #[must_use]
1630     pub fn into_status(&self) -> ExitStatus {
1631         ExitStatus(self.0.into())
1632     }
1633 }
1634
1635 #[unstable(feature = "exit_status_error", issue = "84908")]
1636 impl Into<ExitStatus> for ExitStatusError {
1637     fn into(self) -> ExitStatus {
1638         ExitStatus(self.0.into())
1639     }
1640 }
1641
1642 #[unstable(feature = "exit_status_error", issue = "84908")]
1643 impl fmt::Display for ExitStatusError {
1644     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1645         write!(f, "process exited unsuccessfully: {}", self.into_status())
1646     }
1647 }
1648
1649 #[unstable(feature = "exit_status_error", issue = "84908")]
1650 impl crate::error::Error for ExitStatusError {}
1651
1652 /// This type represents the status code a process can return to its
1653 /// parent under normal termination.
1654 ///
1655 /// Numeric values used in this type don't have portable meanings, and
1656 /// different platforms may mask different amounts of them.
1657 ///
1658 /// For the platform's canonical successful and unsuccessful codes, see
1659 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1660 ///
1661 /// [`SUCCESS`]: ExitCode::SUCCESS
1662 /// [`FAILURE`]: ExitCode::FAILURE
1663 ///
1664 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1665 /// it was ultimately cut from that RFC, and thus this type is more subject
1666 /// to change even than the usual unstable item churn.
1667 ///
1668 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1669 #[derive(Clone, Copy, Debug)]
1670 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1671 pub struct ExitCode(imp::ExitCode);
1672
1673 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1674 impl ExitCode {
1675     /// The canonical ExitCode for successful termination on this platform.
1676     ///
1677     /// Note that a `()`-returning `main` implicitly results in a successful
1678     /// termination, so there's no need to return this from `main` unless
1679     /// you're also returning other possible codes.
1680     #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1681     pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1682
1683     /// The canonical ExitCode for unsuccessful termination on this platform.
1684     ///
1685     /// If you're only returning this and `SUCCESS` from `main`, consider
1686     /// instead returning `Err(_)` and `Ok(())` respectively, which will
1687     /// return the same codes (but will also `eprintln!` the error).
1688     #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1689     pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1690 }
1691
1692 impl Child {
1693     /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1694     /// error is returned.
1695     ///
1696     /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1697     ///
1698     /// This is equivalent to sending a SIGKILL on Unix platforms.
1699     ///
1700     /// # Examples
1701     ///
1702     /// Basic usage:
1703     ///
1704     /// ```no_run
1705     /// use std::process::Command;
1706     ///
1707     /// let mut command = Command::new("yes");
1708     /// if let Ok(mut child) = command.spawn() {
1709     ///     child.kill().expect("command wasn't running");
1710     /// } else {
1711     ///     println!("yes command didn't start");
1712     /// }
1713     /// ```
1714     ///
1715     /// [`ErrorKind`]: io::ErrorKind
1716     /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1717     #[stable(feature = "process", since = "1.0.0")]
1718     pub fn kill(&mut self) -> io::Result<()> {
1719         self.handle.kill()
1720     }
1721
1722     /// Returns the OS-assigned process identifier associated with this child.
1723     ///
1724     /// # Examples
1725     ///
1726     /// Basic usage:
1727     ///
1728     /// ```no_run
1729     /// use std::process::Command;
1730     ///
1731     /// let mut command = Command::new("ls");
1732     /// if let Ok(child) = command.spawn() {
1733     ///     println!("Child's ID is {}", child.id());
1734     /// } else {
1735     ///     println!("ls command didn't start");
1736     /// }
1737     /// ```
1738     #[must_use]
1739     #[stable(feature = "process_id", since = "1.3.0")]
1740     pub fn id(&self) -> u32 {
1741         self.handle.id()
1742     }
1743
1744     /// Waits for the child to exit completely, returning the status that it
1745     /// exited with. This function will continue to have the same return value
1746     /// after it has been called at least once.
1747     ///
1748     /// The stdin handle to the child process, if any, will be closed
1749     /// before waiting. This helps avoid deadlock: it ensures that the
1750     /// child does not block waiting for input from the parent, while
1751     /// the parent waits for the child to exit.
1752     ///
1753     /// # Examples
1754     ///
1755     /// Basic usage:
1756     ///
1757     /// ```no_run
1758     /// use std::process::Command;
1759     ///
1760     /// let mut command = Command::new("ls");
1761     /// if let Ok(mut child) = command.spawn() {
1762     ///     child.wait().expect("command wasn't running");
1763     ///     println!("Child has finished its execution!");
1764     /// } else {
1765     ///     println!("ls command didn't start");
1766     /// }
1767     /// ```
1768     #[stable(feature = "process", since = "1.0.0")]
1769     pub fn wait(&mut self) -> io::Result<ExitStatus> {
1770         drop(self.stdin.take());
1771         self.handle.wait().map(ExitStatus)
1772     }
1773
1774     /// Attempts to collect the exit status of the child if it has already
1775     /// exited.
1776     ///
1777     /// This function will not block the calling thread and will only
1778     /// check to see if the child process has exited or not. If the child has
1779     /// exited then on Unix the process ID is reaped. This function is
1780     /// guaranteed to repeatedly return a successful exit status so long as the
1781     /// child has already exited.
1782     ///
1783     /// If the child has exited, then `Ok(Some(status))` is returned. If the
1784     /// exit status is not available at this time then `Ok(None)` is returned.
1785     /// If an error occurs, then that error is returned.
1786     ///
1787     /// Note that unlike `wait`, this function will not attempt to drop stdin.
1788     ///
1789     /// # Examples
1790     ///
1791     /// Basic usage:
1792     ///
1793     /// ```no_run
1794     /// use std::process::Command;
1795     ///
1796     /// let mut child = Command::new("ls").spawn().unwrap();
1797     ///
1798     /// match child.try_wait() {
1799     ///     Ok(Some(status)) => println!("exited with: {}", status),
1800     ///     Ok(None) => {
1801     ///         println!("status not ready yet, let's really wait");
1802     ///         let res = child.wait();
1803     ///         println!("result: {:?}", res);
1804     ///     }
1805     ///     Err(e) => println!("error attempting to wait: {}", e),
1806     /// }
1807     /// ```
1808     #[stable(feature = "process_try_wait", since = "1.18.0")]
1809     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1810         Ok(self.handle.try_wait()?.map(ExitStatus))
1811     }
1812
1813     /// Simultaneously waits for the child to exit and collect all remaining
1814     /// output on the stdout/stderr handles, returning an `Output`
1815     /// instance.
1816     ///
1817     /// The stdin handle to the child process, if any, will be closed
1818     /// before waiting. This helps avoid deadlock: it ensures that the
1819     /// child does not block waiting for input from the parent, while
1820     /// the parent waits for the child to exit.
1821     ///
1822     /// By default, stdin, stdout and stderr are inherited from the parent.
1823     /// In order to capture the output into this `Result<Output>` it is
1824     /// necessary to create new pipes between parent and child. Use
1825     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1826     ///
1827     /// # Examples
1828     ///
1829     /// ```should_panic
1830     /// use std::process::{Command, Stdio};
1831     ///
1832     /// let child = Command::new("/bin/cat")
1833     ///     .arg("file.txt")
1834     ///     .stdout(Stdio::piped())
1835     ///     .spawn()
1836     ///     .expect("failed to execute child");
1837     ///
1838     /// let output = child
1839     ///     .wait_with_output()
1840     ///     .expect("failed to wait on child");
1841     ///
1842     /// assert!(output.status.success());
1843     /// ```
1844     ///
1845     #[stable(feature = "process", since = "1.0.0")]
1846     pub fn wait_with_output(mut self) -> io::Result<Output> {
1847         drop(self.stdin.take());
1848
1849         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1850         match (self.stdout.take(), self.stderr.take()) {
1851             (None, None) => {}
1852             (Some(mut out), None) => {
1853                 let res = out.read_to_end(&mut stdout);
1854                 res.unwrap();
1855             }
1856             (None, Some(mut err)) => {
1857                 let res = err.read_to_end(&mut stderr);
1858                 res.unwrap();
1859             }
1860             (Some(out), Some(err)) => {
1861                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1862                 res.unwrap();
1863             }
1864         }
1865
1866         let status = self.wait()?;
1867         Ok(Output { status, stdout, stderr })
1868     }
1869 }
1870
1871 /// Terminates the current process with the specified exit code.
1872 ///
1873 /// This function will never return and will immediately terminate the current
1874 /// process. The exit code is passed through to the underlying OS and will be
1875 /// available for consumption by another process.
1876 ///
1877 /// Note that because this function never returns, and that it terminates the
1878 /// process, no destructors on the current stack or any other thread's stack
1879 /// will be run. If a clean shutdown is needed it is recommended to only call
1880 /// this function at a known point where there are no more destructors left
1881 /// to run.
1882 ///
1883 /// ## Platform-specific behavior
1884 ///
1885 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1886 /// will be visible to a parent process inspecting the exit code. On most
1887 /// Unix-like platforms, only the eight least-significant bits are considered.
1888 ///
1889 /// # Examples
1890 ///
1891 /// Due to this function’s behavior regarding destructors, a conventional way
1892 /// to use the function is to extract the actual computation to another
1893 /// function and compute the exit code from its return value:
1894 ///
1895 /// ```
1896 /// fn run_app() -> Result<(), ()> {
1897 ///     // Application logic here
1898 ///     Ok(())
1899 /// }
1900 ///
1901 /// fn main() {
1902 ///     std::process::exit(match run_app() {
1903 ///         Ok(_) => 0,
1904 ///         Err(err) => {
1905 ///             eprintln!("error: {:?}", err);
1906 ///             1
1907 ///         }
1908 ///     });
1909 /// }
1910 /// ```
1911 ///
1912 /// Due to [platform-specific behavior], the exit code for this example will be
1913 /// `0` on Linux, but `256` on Windows:
1914 ///
1915 /// ```no_run
1916 /// use std::process;
1917 ///
1918 /// process::exit(0x0100);
1919 /// ```
1920 ///
1921 /// [platform-specific behavior]: #platform-specific-behavior
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 pub fn exit(code: i32) -> ! {
1924     crate::rt::cleanup();
1925     crate::sys::os::exit(code)
1926 }
1927
1928 /// Terminates the process in an abnormal fashion.
1929 ///
1930 /// The function will never return and will immediately terminate the current
1931 /// process in a platform specific "abnormal" manner.
1932 ///
1933 /// Note that because this function never returns, and that it terminates the
1934 /// process, no destructors on the current stack or any other thread's stack
1935 /// will be run.
1936 ///
1937 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
1938 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
1939 ///
1940 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1941 /// the current thread's stack and calls all destructors.
1942 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1943 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1944 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1945 ///
1946 /// If a clean shutdown is needed it is recommended to only call
1947 /// this function at a known point where there are no more destructors left
1948 /// to run.
1949 ///
1950 /// The process's termination will be similar to that from the C `abort()`
1951 /// function.  On Unix, the process will terminate with signal `SIGABRT`, which
1952 /// typically means that the shell prints "Aborted".
1953 ///
1954 /// # Examples
1955 ///
1956 /// ```no_run
1957 /// use std::process;
1958 ///
1959 /// fn main() {
1960 ///     println!("aborting");
1961 ///
1962 ///     process::abort();
1963 ///
1964 ///     // execution never gets here
1965 /// }
1966 /// ```
1967 ///
1968 /// The `abort` function terminates the process, so the destructor will not
1969 /// get run on the example below:
1970 ///
1971 /// ```no_run
1972 /// use std::process;
1973 ///
1974 /// struct HasDrop;
1975 ///
1976 /// impl Drop for HasDrop {
1977 ///     fn drop(&mut self) {
1978 ///         println!("This will never be printed!");
1979 ///     }
1980 /// }
1981 ///
1982 /// fn main() {
1983 ///     let _x = HasDrop;
1984 ///     process::abort();
1985 ///     // the destructor implemented for HasDrop will never get run
1986 /// }
1987 /// ```
1988 ///
1989 /// [panic hook]: crate::panic::set_hook
1990 #[stable(feature = "process_abort", since = "1.17.0")]
1991 #[cold]
1992 pub fn abort() -> ! {
1993     crate::sys::abort_internal();
1994 }
1995
1996 /// Returns the OS-assigned process identifier associated with this process.
1997 ///
1998 /// # Examples
1999 ///
2000 /// Basic usage:
2001 ///
2002 /// ```no_run
2003 /// use std::process;
2004 ///
2005 /// println!("My pid is {}", process::id());
2006 /// ```
2007 ///
2008 ///
2009 #[must_use]
2010 #[stable(feature = "getpid", since = "1.26.0")]
2011 pub fn id() -> u32 {
2012     crate::sys::os::getpid()
2013 }
2014
2015 /// A trait for implementing arbitrary return types in the `main` function.
2016 ///
2017 /// The C-main function only supports to return integers as return type.
2018 /// So, every type implementing the `Termination` trait has to be converted
2019 /// to an integer.
2020 ///
2021 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2022 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2023 #[cfg_attr(not(test), lang = "termination")]
2024 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2025 #[rustc_on_unimplemented(
2026     message = "`main` has invalid return type `{Self}`",
2027     label = "`main` can only return types that implement `{Termination}`"
2028 )]
2029 pub trait Termination {
2030     /// Is called to get the representation of the value as status code.
2031     /// This status code is returned to the operating system.
2032     fn report(self) -> i32;
2033 }
2034
2035 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2036 impl Termination for () {
2037     #[inline]
2038     fn report(self) -> i32 {
2039         ExitCode::SUCCESS.report()
2040     }
2041 }
2042
2043 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2044 impl<E: fmt::Debug> Termination for Result<(), E> {
2045     fn report(self) -> i32 {
2046         match self {
2047             Ok(()) => ().report(),
2048             Err(err) => Err::<!, _>(err).report(),
2049         }
2050     }
2051 }
2052
2053 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2054 impl Termination for ! {
2055     fn report(self) -> i32 {
2056         self
2057     }
2058 }
2059
2060 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2061 impl<E: fmt::Debug> Termination for Result<!, E> {
2062     fn report(self) -> i32 {
2063         let Err(err) = self;
2064         eprintln!("Error: {:?}", err);
2065         ExitCode::FAILURE.report()
2066     }
2067 }
2068
2069 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2070 impl<E: fmt::Debug> Termination for Result<Infallible, E> {
2071     fn report(self) -> i32 {
2072         let Err(err) = self;
2073         Err::<!, _>(err).report()
2074     }
2075 }
2076
2077 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2078 impl Termination for ExitCode {
2079     #[inline]
2080     fn report(self) -> i32 {
2081         self.0.as_i32()
2082     }
2083 }