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