]> git.lizzy.rs Git - rust.git/blob - library/std/src/process.rs
Rollup merge of #90704 - ijackson:exitstatus-comments, r=joshtriplett
[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     #[must_use]
952     #[stable(feature = "command_access", since = "1.57.0")]
953     pub fn get_program(&self) -> &OsStr {
954         self.inner.get_program()
955     }
956
957     /// Returns an iterator of the arguments that will be passed to the program.
958     ///
959     /// This does not include the path to the program as the first argument;
960     /// it only includes the arguments specified with [`Command::arg`] and
961     /// [`Command::args`].
962     ///
963     /// # Examples
964     ///
965     /// ```
966     /// use std::ffi::OsStr;
967     /// use std::process::Command;
968     ///
969     /// let mut cmd = Command::new("echo");
970     /// cmd.arg("first").arg("second");
971     /// let args: Vec<&OsStr> = cmd.get_args().collect();
972     /// assert_eq!(args, &["first", "second"]);
973     /// ```
974     #[stable(feature = "command_access", since = "1.57.0")]
975     pub fn get_args(&self) -> CommandArgs<'_> {
976         CommandArgs { inner: self.inner.get_args() }
977     }
978
979     /// Returns an iterator of the environment variables that will be set when
980     /// the process is spawned.
981     ///
982     /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first
983     /// value is the key, and the second is the value, which is [`None`] if
984     /// the environment variable is to be explicitly removed.
985     ///
986     /// This only includes environment variables explicitly set with
987     /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It
988     /// does not include environment variables that will be inherited by the
989     /// child process.
990     ///
991     /// # Examples
992     ///
993     /// ```
994     /// use std::ffi::OsStr;
995     /// use std::process::Command;
996     ///
997     /// let mut cmd = Command::new("ls");
998     /// cmd.env("TERM", "dumb").env_remove("TZ");
999     /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1000     /// assert_eq!(envs, &[
1001     ///     (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1002     ///     (OsStr::new("TZ"), None)
1003     /// ]);
1004     /// ```
1005     #[stable(feature = "command_access", since = "1.57.0")]
1006     pub fn get_envs(&self) -> CommandEnvs<'_> {
1007         self.inner.get_envs()
1008     }
1009
1010     /// Returns the working directory for the child process.
1011     ///
1012     /// This returns [`None`] if the working directory will not be changed.
1013     ///
1014     /// # Examples
1015     ///
1016     /// ```
1017     /// use std::path::Path;
1018     /// use std::process::Command;
1019     ///
1020     /// let mut cmd = Command::new("ls");
1021     /// assert_eq!(cmd.get_current_dir(), None);
1022     /// cmd.current_dir("/bin");
1023     /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1024     /// ```
1025     #[must_use]
1026     #[stable(feature = "command_access", since = "1.57.0")]
1027     pub fn get_current_dir(&self) -> Option<&Path> {
1028         self.inner.get_current_dir()
1029     }
1030 }
1031
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 impl fmt::Debug for Command {
1034     /// Format the program and arguments of a Command for display. Any
1035     /// non-utf8 data is lossily converted using the utf8 replacement
1036     /// character.
1037     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1038         self.inner.fmt(f)
1039     }
1040 }
1041
1042 impl AsInner<imp::Command> for Command {
1043     fn as_inner(&self) -> &imp::Command {
1044         &self.inner
1045     }
1046 }
1047
1048 impl AsInnerMut<imp::Command> for Command {
1049     fn as_inner_mut(&mut self) -> &mut imp::Command {
1050         &mut self.inner
1051     }
1052 }
1053
1054 /// An iterator over the command arguments.
1055 ///
1056 /// This struct is created by [`Command::get_args`]. See its documentation for
1057 /// more.
1058 #[must_use = "iterators are lazy and do nothing unless consumed"]
1059 #[stable(feature = "command_access", since = "1.57.0")]
1060 #[derive(Debug)]
1061 pub struct CommandArgs<'a> {
1062     inner: imp::CommandArgs<'a>,
1063 }
1064
1065 #[stable(feature = "command_access", since = "1.57.0")]
1066 impl<'a> Iterator for CommandArgs<'a> {
1067     type Item = &'a OsStr;
1068     fn next(&mut self) -> Option<&'a OsStr> {
1069         self.inner.next()
1070     }
1071     fn size_hint(&self) -> (usize, Option<usize>) {
1072         self.inner.size_hint()
1073     }
1074 }
1075
1076 #[stable(feature = "command_access", since = "1.57.0")]
1077 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1078     fn len(&self) -> usize {
1079         self.inner.len()
1080     }
1081     fn is_empty(&self) -> bool {
1082         self.inner.is_empty()
1083     }
1084 }
1085
1086 /// The output of a finished process.
1087 ///
1088 /// This is returned in a Result by either the [`output`] method of a
1089 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1090 /// process.
1091 ///
1092 /// [`output`]: Command::output
1093 /// [`wait_with_output`]: Child::wait_with_output
1094 #[derive(PartialEq, Eq, Clone)]
1095 #[stable(feature = "process", since = "1.0.0")]
1096 pub struct Output {
1097     /// The status (exit code) of the process.
1098     #[stable(feature = "process", since = "1.0.0")]
1099     pub status: ExitStatus,
1100     /// The data that the process wrote to stdout.
1101     #[stable(feature = "process", since = "1.0.0")]
1102     pub stdout: Vec<u8>,
1103     /// The data that the process wrote to stderr.
1104     #[stable(feature = "process", since = "1.0.0")]
1105     pub stderr: Vec<u8>,
1106 }
1107
1108 // If either stderr or stdout are valid utf8 strings it prints the valid
1109 // strings, otherwise it prints the byte sequence instead
1110 #[stable(feature = "process_output_debug", since = "1.7.0")]
1111 impl fmt::Debug for Output {
1112     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1113         let stdout_utf8 = str::from_utf8(&self.stdout);
1114         let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1115             Ok(ref str) => str,
1116             Err(_) => &self.stdout,
1117         };
1118
1119         let stderr_utf8 = str::from_utf8(&self.stderr);
1120         let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1121             Ok(ref str) => str,
1122             Err(_) => &self.stderr,
1123         };
1124
1125         fmt.debug_struct("Output")
1126             .field("status", &self.status)
1127             .field("stdout", stdout_debug)
1128             .field("stderr", stderr_debug)
1129             .finish()
1130     }
1131 }
1132
1133 /// Describes what to do with a standard I/O stream for a child process when
1134 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1135 ///
1136 /// [`stdin`]: Command::stdin
1137 /// [`stdout`]: Command::stdout
1138 /// [`stderr`]: Command::stderr
1139 #[stable(feature = "process", since = "1.0.0")]
1140 pub struct Stdio(imp::Stdio);
1141
1142 impl Stdio {
1143     /// A new pipe should be arranged to connect the parent and child processes.
1144     ///
1145     /// # Examples
1146     ///
1147     /// With stdout:
1148     ///
1149     /// ```no_run
1150     /// use std::process::{Command, Stdio};
1151     ///
1152     /// let output = Command::new("echo")
1153     ///     .arg("Hello, world!")
1154     ///     .stdout(Stdio::piped())
1155     ///     .output()
1156     ///     .expect("Failed to execute command");
1157     ///
1158     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1159     /// // Nothing echoed to console
1160     /// ```
1161     ///
1162     /// With stdin:
1163     ///
1164     /// ```no_run
1165     /// use std::io::Write;
1166     /// use std::process::{Command, Stdio};
1167     ///
1168     /// let mut child = Command::new("rev")
1169     ///     .stdin(Stdio::piped())
1170     ///     .stdout(Stdio::piped())
1171     ///     .spawn()
1172     ///     .expect("Failed to spawn child process");
1173     ///
1174     /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1175     /// std::thread::spawn(move || {
1176     ///     stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1177     /// });
1178     ///
1179     /// let output = child.wait_with_output().expect("Failed to read stdout");
1180     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1181     /// ```
1182     ///
1183     /// Writing more than a pipe buffer's worth of input to stdin without also reading
1184     /// stdout and stderr at the same time may cause a deadlock.
1185     /// This is an issue when running any program that doesn't guarantee that it reads
1186     /// its entire stdin before writing more than a pipe buffer's worth of output.
1187     /// The size of a pipe buffer varies on different targets.
1188     ///
1189     #[must_use]
1190     #[stable(feature = "process", since = "1.0.0")]
1191     pub fn piped() -> Stdio {
1192         Stdio(imp::Stdio::MakePipe)
1193     }
1194
1195     /// The child inherits from the corresponding parent descriptor.
1196     ///
1197     /// # Examples
1198     ///
1199     /// With stdout:
1200     ///
1201     /// ```no_run
1202     /// use std::process::{Command, Stdio};
1203     ///
1204     /// let output = Command::new("echo")
1205     ///     .arg("Hello, world!")
1206     ///     .stdout(Stdio::inherit())
1207     ///     .output()
1208     ///     .expect("Failed to execute command");
1209     ///
1210     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1211     /// // "Hello, world!" echoed to console
1212     /// ```
1213     ///
1214     /// With stdin:
1215     ///
1216     /// ```no_run
1217     /// use std::process::{Command, Stdio};
1218     /// use std::io::{self, Write};
1219     ///
1220     /// let output = Command::new("rev")
1221     ///     .stdin(Stdio::inherit())
1222     ///     .stdout(Stdio::piped())
1223     ///     .output()
1224     ///     .expect("Failed to execute command");
1225     ///
1226     /// print!("You piped in the reverse of: ");
1227     /// io::stdout().write_all(&output.stdout).unwrap();
1228     /// ```
1229     #[must_use]
1230     #[stable(feature = "process", since = "1.0.0")]
1231     pub fn inherit() -> Stdio {
1232         Stdio(imp::Stdio::Inherit)
1233     }
1234
1235     /// This stream will be ignored. This is the equivalent of attaching the
1236     /// stream to `/dev/null`.
1237     ///
1238     /// # Examples
1239     ///
1240     /// With stdout:
1241     ///
1242     /// ```no_run
1243     /// use std::process::{Command, Stdio};
1244     ///
1245     /// let output = Command::new("echo")
1246     ///     .arg("Hello, world!")
1247     ///     .stdout(Stdio::null())
1248     ///     .output()
1249     ///     .expect("Failed to execute command");
1250     ///
1251     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1252     /// // Nothing echoed to console
1253     /// ```
1254     ///
1255     /// With stdin:
1256     ///
1257     /// ```no_run
1258     /// use std::process::{Command, Stdio};
1259     ///
1260     /// let output = Command::new("rev")
1261     ///     .stdin(Stdio::null())
1262     ///     .stdout(Stdio::piped())
1263     ///     .output()
1264     ///     .expect("Failed to execute command");
1265     ///
1266     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1267     /// // Ignores any piped-in input
1268     /// ```
1269     #[must_use]
1270     #[stable(feature = "process", since = "1.0.0")]
1271     pub fn null() -> Stdio {
1272         Stdio(imp::Stdio::Null)
1273     }
1274 }
1275
1276 impl FromInner<imp::Stdio> for Stdio {
1277     fn from_inner(inner: imp::Stdio) -> Stdio {
1278         Stdio(inner)
1279     }
1280 }
1281
1282 #[stable(feature = "std_debug", since = "1.16.0")]
1283 impl fmt::Debug for Stdio {
1284     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1285         f.debug_struct("Stdio").finish_non_exhaustive()
1286     }
1287 }
1288
1289 #[stable(feature = "stdio_from", since = "1.20.0")]
1290 impl From<ChildStdin> for Stdio {
1291     /// Converts a `ChildStdin` into a `Stdio`
1292     ///
1293     /// # Examples
1294     ///
1295     /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1296     ///
1297     /// ```rust,no_run
1298     /// use std::process::{Command, Stdio};
1299     ///
1300     /// let reverse = Command::new("rev")
1301     ///     .stdin(Stdio::piped())
1302     ///     .spawn()
1303     ///     .expect("failed reverse command");
1304     ///
1305     /// let _echo = Command::new("echo")
1306     ///     .arg("Hello, world!")
1307     ///     .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1308     ///     .output()
1309     ///     .expect("failed echo command");
1310     ///
1311     /// // "!dlrow ,olleH" echoed to console
1312     /// ```
1313     fn from(child: ChildStdin) -> Stdio {
1314         Stdio::from_inner(child.into_inner().into())
1315     }
1316 }
1317
1318 #[stable(feature = "stdio_from", since = "1.20.0")]
1319 impl From<ChildStdout> for Stdio {
1320     /// Converts a `ChildStdout` into a `Stdio`
1321     ///
1322     /// # Examples
1323     ///
1324     /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1325     ///
1326     /// ```rust,no_run
1327     /// use std::process::{Command, Stdio};
1328     ///
1329     /// let hello = Command::new("echo")
1330     ///     .arg("Hello, world!")
1331     ///     .stdout(Stdio::piped())
1332     ///     .spawn()
1333     ///     .expect("failed echo command");
1334     ///
1335     /// let reverse = Command::new("rev")
1336     ///     .stdin(hello.stdout.unwrap())  // Converted into a Stdio here
1337     ///     .output()
1338     ///     .expect("failed reverse command");
1339     ///
1340     /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1341     /// ```
1342     fn from(child: ChildStdout) -> Stdio {
1343         Stdio::from_inner(child.into_inner().into())
1344     }
1345 }
1346
1347 #[stable(feature = "stdio_from", since = "1.20.0")]
1348 impl From<ChildStderr> for Stdio {
1349     /// Converts a `ChildStderr` into a `Stdio`
1350     ///
1351     /// # Examples
1352     ///
1353     /// ```rust,no_run
1354     /// use std::process::{Command, Stdio};
1355     ///
1356     /// let reverse = Command::new("rev")
1357     ///     .arg("non_existing_file.txt")
1358     ///     .stderr(Stdio::piped())
1359     ///     .spawn()
1360     ///     .expect("failed reverse command");
1361     ///
1362     /// let cat = Command::new("cat")
1363     ///     .arg("-")
1364     ///     .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1365     ///     .output()
1366     ///     .expect("failed echo command");
1367     ///
1368     /// assert_eq!(
1369     ///     String::from_utf8_lossy(&cat.stdout),
1370     ///     "rev: cannot open non_existing_file.txt: No such file or directory\n"
1371     /// );
1372     /// ```
1373     fn from(child: ChildStderr) -> Stdio {
1374         Stdio::from_inner(child.into_inner().into())
1375     }
1376 }
1377
1378 #[stable(feature = "stdio_from", since = "1.20.0")]
1379 impl From<fs::File> for Stdio {
1380     /// Converts a `File` into a `Stdio`
1381     ///
1382     /// # Examples
1383     ///
1384     /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1385     ///
1386     /// ```rust,no_run
1387     /// use std::fs::File;
1388     /// use std::process::Command;
1389     ///
1390     /// // With the `foo.txt` file containing `Hello, world!"
1391     /// let file = File::open("foo.txt").unwrap();
1392     ///
1393     /// let reverse = Command::new("rev")
1394     ///     .stdin(file)  // Implicit File conversion into a Stdio
1395     ///     .output()
1396     ///     .expect("failed reverse command");
1397     ///
1398     /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1399     /// ```
1400     fn from(file: fs::File) -> Stdio {
1401         Stdio::from_inner(file.into_inner().into())
1402     }
1403 }
1404
1405 /// Describes the result of a process after it has terminated.
1406 ///
1407 /// This `struct` is used to represent the exit status or other termination of a child process.
1408 /// Child processes are created via the [`Command`] struct and their exit
1409 /// status is exposed through the [`status`] method, or the [`wait`] method
1410 /// of a [`Child`] process.
1411 ///
1412 /// An `ExitStatus` represents every possible disposition of a process.  On Unix this
1413 /// is the **wait status**.  It is *not* simply an *exit status* (a value passed to `exit`).
1414 ///
1415 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1416 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1417 ///
1418 /// [`status`]: Command::status
1419 /// [`wait`]: Child::wait
1420 //
1421 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1422 // vs `_exit`.  Naming of Unix system calls is not standardised across Unices, so terminology is a
1423 // matter of convention and tradition.  For clarity we usually speak of `exit`, even when we might
1424 // mean an underlying system call such as `_exit`.
1425 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1426 #[stable(feature = "process", since = "1.0.0")]
1427 pub struct ExitStatus(imp::ExitStatus);
1428
1429 /// Allows extension traits within `std`.
1430 #[unstable(feature = "sealed", issue = "none")]
1431 impl crate::sealed::Sealed for ExitStatus {}
1432
1433 impl ExitStatus {
1434     /// Was termination successful?  Returns a `Result`.
1435     ///
1436     /// # Examples
1437     ///
1438     /// ```
1439     /// #![feature(exit_status_error)]
1440     /// # if cfg!(unix) {
1441     /// use std::process::Command;
1442     ///
1443     /// let status = Command::new("ls")
1444     ///                      .arg("/dev/nonexistent")
1445     ///                      .status()
1446     ///                      .expect("ls could not be executed");
1447     ///
1448     /// println!("ls: {}", status);
1449     /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1450     /// # } // cfg!(unix)
1451     /// ```
1452     #[unstable(feature = "exit_status_error", issue = "84908")]
1453     pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1454         self.0.exit_ok().map_err(ExitStatusError)
1455     }
1456
1457     /// Was termination successful? Signal termination is not considered a
1458     /// success, and success is defined as a zero exit status.
1459     ///
1460     /// # Examples
1461     ///
1462     /// ```rust,no_run
1463     /// use std::process::Command;
1464     ///
1465     /// let status = Command::new("mkdir")
1466     ///                      .arg("projects")
1467     ///                      .status()
1468     ///                      .expect("failed to execute mkdir");
1469     ///
1470     /// if status.success() {
1471     ///     println!("'projects/' directory created");
1472     /// } else {
1473     ///     println!("failed to create 'projects/' directory: {}", status);
1474     /// }
1475     /// ```
1476     #[must_use]
1477     #[stable(feature = "process", since = "1.0.0")]
1478     pub fn success(&self) -> bool {
1479         self.0.exit_ok().is_ok()
1480     }
1481
1482     /// Returns the exit code of the process, if any.
1483     ///
1484     /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1485     /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1486     /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1487     /// runtime system (often, for example, 255, 254, 127 or 126).
1488     ///
1489     /// On Unix, this will return `None` if the process was terminated by a signal.
1490     /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1491     /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1492     ///
1493     /// # Examples
1494     ///
1495     /// ```no_run
1496     /// use std::process::Command;
1497     ///
1498     /// let status = Command::new("mkdir")
1499     ///                      .arg("projects")
1500     ///                      .status()
1501     ///                      .expect("failed to execute mkdir");
1502     ///
1503     /// match status.code() {
1504     ///     Some(code) => println!("Exited with status code: {}", code),
1505     ///     None       => println!("Process terminated by signal")
1506     /// }
1507     /// ```
1508     #[must_use]
1509     #[stable(feature = "process", since = "1.0.0")]
1510     pub fn code(&self) -> Option<i32> {
1511         self.0.code()
1512     }
1513 }
1514
1515 impl AsInner<imp::ExitStatus> for ExitStatus {
1516     fn as_inner(&self) -> &imp::ExitStatus {
1517         &self.0
1518     }
1519 }
1520
1521 impl FromInner<imp::ExitStatus> for ExitStatus {
1522     fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1523         ExitStatus(s)
1524     }
1525 }
1526
1527 #[stable(feature = "process", since = "1.0.0")]
1528 impl fmt::Display for ExitStatus {
1529     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1530         self.0.fmt(f)
1531     }
1532 }
1533
1534 /// Allows extension traits within `std`.
1535 #[unstable(feature = "sealed", issue = "none")]
1536 impl crate::sealed::Sealed for ExitStatusError {}
1537
1538 /// Describes the result of a process after it has failed
1539 ///
1540 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1541 ///
1542 /// # Examples
1543 ///
1544 /// ```
1545 /// #![feature(exit_status_error)]
1546 /// # if cfg!(unix) {
1547 /// use std::process::{Command, ExitStatusError};
1548 ///
1549 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1550 ///     Command::new(cmd).status().unwrap().exit_ok()?;
1551 ///     Ok(())
1552 /// }
1553 ///
1554 /// run("true").unwrap();
1555 /// run("false").unwrap_err();
1556 /// # } // cfg!(unix)
1557 /// ```
1558 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1559 #[unstable(feature = "exit_status_error", issue = "84908")]
1560 // The definition of imp::ExitStatusError should ideally be such that
1561 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1562 pub struct ExitStatusError(imp::ExitStatusError);
1563
1564 #[unstable(feature = "exit_status_error", issue = "84908")]
1565 impl ExitStatusError {
1566     /// Reports the exit code, if applicable, from an `ExitStatusError`.
1567     ///
1568     /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1569     /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1570     /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1571     /// runtime system (often, for example, 255, 254, 127 or 126).
1572     ///
1573     /// On Unix, this will return `None` if the process was terminated by a signal.  If you want to
1574     /// handle such situations specially, consider using methods from
1575     /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1576     ///
1577     /// If the process finished by calling `exit` with a nonzero value, this will return
1578     /// that exit status.
1579     ///
1580     /// If the error was something else, it will return `None`.
1581     ///
1582     /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1583     /// `ExitStatusError`.  So the return value from `ExitStatusError::code()` is always nonzero.
1584     ///
1585     /// # Examples
1586     ///
1587     /// ```
1588     /// #![feature(exit_status_error)]
1589     /// # #[cfg(unix)] {
1590     /// use std::process::Command;
1591     ///
1592     /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1593     /// assert_eq!(bad.code(), Some(1));
1594     /// # } // #[cfg(unix)]
1595     /// ```
1596     #[must_use]
1597     pub fn code(&self) -> Option<i32> {
1598         self.code_nonzero().map(Into::into)
1599     }
1600
1601     /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1602     ///
1603     /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1604     ///
1605     /// Plain `code`, returning a plain integer, is provided because is is often more convenient.
1606     /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1607     /// a type-level guarantee of nonzeroness.
1608     ///
1609     /// # Examples
1610     ///
1611     /// ```
1612     /// #![feature(exit_status_error)]
1613     /// # if cfg!(unix) {
1614     /// use std::convert::TryFrom;
1615     /// use std::num::NonZeroI32;
1616     /// use std::process::Command;
1617     ///
1618     /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1619     /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1620     /// # } // cfg!(unix)
1621     /// ```
1622     #[must_use]
1623     pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1624         self.0.code()
1625     }
1626
1627     /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1628     #[must_use]
1629     pub fn into_status(&self) -> ExitStatus {
1630         ExitStatus(self.0.into())
1631     }
1632 }
1633
1634 #[unstable(feature = "exit_status_error", issue = "84908")]
1635 impl Into<ExitStatus> for ExitStatusError {
1636     fn into(self) -> ExitStatus {
1637         ExitStatus(self.0.into())
1638     }
1639 }
1640
1641 #[unstable(feature = "exit_status_error", issue = "84908")]
1642 impl fmt::Display for ExitStatusError {
1643     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1644         write!(f, "process exited unsuccessfully: {}", self.into_status())
1645     }
1646 }
1647
1648 #[unstable(feature = "exit_status_error", issue = "84908")]
1649 impl crate::error::Error for ExitStatusError {}
1650
1651 /// This type represents the status code a process can return to its
1652 /// parent under normal termination.
1653 ///
1654 /// Numeric values used in this type don't have portable meanings, and
1655 /// different platforms may mask different amounts of them.
1656 ///
1657 /// For the platform's canonical successful and unsuccessful codes, see
1658 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1659 ///
1660 /// [`SUCCESS`]: ExitCode::SUCCESS
1661 /// [`FAILURE`]: ExitCode::FAILURE
1662 ///
1663 /// **Warning**: While various forms of this were discussed in [RFC #1937],
1664 /// it was ultimately cut from that RFC, and thus this type is more subject
1665 /// to change even than the usual unstable item churn.
1666 ///
1667 /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
1668 #[derive(Clone, Copy, Debug)]
1669 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1670 pub struct ExitCode(imp::ExitCode);
1671
1672 #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1673 impl ExitCode {
1674     /// The canonical ExitCode for successful termination on this platform.
1675     ///
1676     /// Note that a `()`-returning `main` implicitly results in a successful
1677     /// termination, so there's no need to return this from `main` unless
1678     /// you're also returning other possible codes.
1679     #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1680     pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1681
1682     /// The canonical ExitCode for unsuccessful termination on this platform.
1683     ///
1684     /// If you're only returning this and `SUCCESS` from `main`, consider
1685     /// instead returning `Err(_)` and `Ok(())` respectively, which will
1686     /// return the same codes (but will also `eprintln!` the error).
1687     #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
1688     pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1689 }
1690
1691 impl Child {
1692     /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1693     /// error is returned.
1694     ///
1695     /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1696     ///
1697     /// This is equivalent to sending a SIGKILL on Unix platforms.
1698     ///
1699     /// # Examples
1700     ///
1701     /// Basic usage:
1702     ///
1703     /// ```no_run
1704     /// use std::process::Command;
1705     ///
1706     /// let mut command = Command::new("yes");
1707     /// if let Ok(mut child) = command.spawn() {
1708     ///     child.kill().expect("command wasn't running");
1709     /// } else {
1710     ///     println!("yes command didn't start");
1711     /// }
1712     /// ```
1713     ///
1714     /// [`ErrorKind`]: io::ErrorKind
1715     /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1716     #[stable(feature = "process", since = "1.0.0")]
1717     pub fn kill(&mut self) -> io::Result<()> {
1718         self.handle.kill()
1719     }
1720
1721     /// Returns the OS-assigned process identifier associated with this child.
1722     ///
1723     /// # Examples
1724     ///
1725     /// Basic usage:
1726     ///
1727     /// ```no_run
1728     /// use std::process::Command;
1729     ///
1730     /// let mut command = Command::new("ls");
1731     /// if let Ok(child) = command.spawn() {
1732     ///     println!("Child's ID is {}", child.id());
1733     /// } else {
1734     ///     println!("ls command didn't start");
1735     /// }
1736     /// ```
1737     #[must_use]
1738     #[stable(feature = "process_id", since = "1.3.0")]
1739     pub fn id(&self) -> u32 {
1740         self.handle.id()
1741     }
1742
1743     /// Waits for the child to exit completely, returning the status that it
1744     /// exited with. This function will continue to have the same return value
1745     /// after it has been called at least once.
1746     ///
1747     /// The stdin handle to the child process, if any, will be closed
1748     /// before waiting. This helps avoid deadlock: it ensures that the
1749     /// child does not block waiting for input from the parent, while
1750     /// the parent waits for the child to exit.
1751     ///
1752     /// # Examples
1753     ///
1754     /// Basic usage:
1755     ///
1756     /// ```no_run
1757     /// use std::process::Command;
1758     ///
1759     /// let mut command = Command::new("ls");
1760     /// if let Ok(mut child) = command.spawn() {
1761     ///     child.wait().expect("command wasn't running");
1762     ///     println!("Child has finished its execution!");
1763     /// } else {
1764     ///     println!("ls command didn't start");
1765     /// }
1766     /// ```
1767     #[stable(feature = "process", since = "1.0.0")]
1768     pub fn wait(&mut self) -> io::Result<ExitStatus> {
1769         drop(self.stdin.take());
1770         self.handle.wait().map(ExitStatus)
1771     }
1772
1773     /// Attempts to collect the exit status of the child if it has already
1774     /// exited.
1775     ///
1776     /// This function will not block the calling thread and will only
1777     /// check to see if the child process has exited or not. If the child has
1778     /// exited then on Unix the process ID is reaped. This function is
1779     /// guaranteed to repeatedly return a successful exit status so long as the
1780     /// child has already exited.
1781     ///
1782     /// If the child has exited, then `Ok(Some(status))` is returned. If the
1783     /// exit status is not available at this time then `Ok(None)` is returned.
1784     /// If an error occurs, then that error is returned.
1785     ///
1786     /// Note that unlike `wait`, this function will not attempt to drop stdin.
1787     ///
1788     /// # Examples
1789     ///
1790     /// Basic usage:
1791     ///
1792     /// ```no_run
1793     /// use std::process::Command;
1794     ///
1795     /// let mut child = Command::new("ls").spawn().unwrap();
1796     ///
1797     /// match child.try_wait() {
1798     ///     Ok(Some(status)) => println!("exited with: {}", status),
1799     ///     Ok(None) => {
1800     ///         println!("status not ready yet, let's really wait");
1801     ///         let res = child.wait();
1802     ///         println!("result: {:?}", res);
1803     ///     }
1804     ///     Err(e) => println!("error attempting to wait: {}", e),
1805     /// }
1806     /// ```
1807     #[stable(feature = "process_try_wait", since = "1.18.0")]
1808     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1809         Ok(self.handle.try_wait()?.map(ExitStatus))
1810     }
1811
1812     /// Simultaneously waits for the child to exit and collect all remaining
1813     /// output on the stdout/stderr handles, returning an `Output`
1814     /// instance.
1815     ///
1816     /// The stdin handle to the child process, if any, will be closed
1817     /// before waiting. This helps avoid deadlock: it ensures that the
1818     /// child does not block waiting for input from the parent, while
1819     /// the parent waits for the child to exit.
1820     ///
1821     /// By default, stdin, stdout and stderr are inherited from the parent.
1822     /// In order to capture the output into this `Result<Output>` it is
1823     /// necessary to create new pipes between parent and child. Use
1824     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1825     ///
1826     /// # Examples
1827     ///
1828     /// ```should_panic
1829     /// use std::process::{Command, Stdio};
1830     ///
1831     /// let child = Command::new("/bin/cat")
1832     ///     .arg("file.txt")
1833     ///     .stdout(Stdio::piped())
1834     ///     .spawn()
1835     ///     .expect("failed to execute child");
1836     ///
1837     /// let output = child
1838     ///     .wait_with_output()
1839     ///     .expect("failed to wait on child");
1840     ///
1841     /// assert!(output.status.success());
1842     /// ```
1843     ///
1844     #[stable(feature = "process", since = "1.0.0")]
1845     pub fn wait_with_output(mut self) -> io::Result<Output> {
1846         drop(self.stdin.take());
1847
1848         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1849         match (self.stdout.take(), self.stderr.take()) {
1850             (None, None) => {}
1851             (Some(mut out), None) => {
1852                 let res = out.read_to_end(&mut stdout);
1853                 res.unwrap();
1854             }
1855             (None, Some(mut err)) => {
1856                 let res = err.read_to_end(&mut stderr);
1857                 res.unwrap();
1858             }
1859             (Some(out), Some(err)) => {
1860                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
1861                 res.unwrap();
1862             }
1863         }
1864
1865         let status = self.wait()?;
1866         Ok(Output { status, stdout, stderr })
1867     }
1868 }
1869
1870 /// Terminates the current process with the specified exit code.
1871 ///
1872 /// This function will never return and will immediately terminate the current
1873 /// process. The exit code is passed through to the underlying OS and will be
1874 /// available for consumption by another process.
1875 ///
1876 /// Note that because this function never returns, and that it terminates the
1877 /// process, no destructors on the current stack or any other thread's stack
1878 /// will be run. If a clean shutdown is needed it is recommended to only call
1879 /// this function at a known point where there are no more destructors left
1880 /// to run.
1881 ///
1882 /// ## Platform-specific behavior
1883 ///
1884 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1885 /// will be visible to a parent process inspecting the exit code. On most
1886 /// Unix-like platforms, only the eight least-significant bits are considered.
1887 ///
1888 /// # Examples
1889 ///
1890 /// Due to this function’s behavior regarding destructors, a conventional way
1891 /// to use the function is to extract the actual computation to another
1892 /// function and compute the exit code from its return value:
1893 ///
1894 /// ```
1895 /// fn run_app() -> Result<(), ()> {
1896 ///     // Application logic here
1897 ///     Ok(())
1898 /// }
1899 ///
1900 /// fn main() {
1901 ///     std::process::exit(match run_app() {
1902 ///         Ok(_) => 0,
1903 ///         Err(err) => {
1904 ///             eprintln!("error: {:?}", err);
1905 ///             1
1906 ///         }
1907 ///     });
1908 /// }
1909 /// ```
1910 ///
1911 /// Due to [platform-specific behavior], the exit code for this example will be
1912 /// `0` on Linux, but `256` on Windows:
1913 ///
1914 /// ```no_run
1915 /// use std::process;
1916 ///
1917 /// process::exit(0x0100);
1918 /// ```
1919 ///
1920 /// [platform-specific behavior]: #platform-specific-behavior
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 pub fn exit(code: i32) -> ! {
1923     crate::rt::cleanup();
1924     crate::sys::os::exit(code)
1925 }
1926
1927 /// Terminates the process in an abnormal fashion.
1928 ///
1929 /// The function will never return and will immediately terminate the current
1930 /// process in a platform specific "abnormal" manner.
1931 ///
1932 /// Note that because this function never returns, and that it terminates the
1933 /// process, no destructors on the current stack or any other thread's stack
1934 /// will be run.
1935 ///
1936 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
1937 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
1938 ///
1939 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
1940 /// the current thread's stack and calls all destructors.
1941 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
1942 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
1943 /// [`panic!`] will still call the [panic hook] while `abort` will not.
1944 ///
1945 /// If a clean shutdown is needed it is recommended to only call
1946 /// this function at a known point where there are no more destructors left
1947 /// to run.
1948 ///
1949 /// The process's termination will be similar to that from the C `abort()`
1950 /// function.  On Unix, the process will terminate with signal `SIGABRT`, which
1951 /// typically means that the shell prints "Aborted".
1952 ///
1953 /// # Examples
1954 ///
1955 /// ```no_run
1956 /// use std::process;
1957 ///
1958 /// fn main() {
1959 ///     println!("aborting");
1960 ///
1961 ///     process::abort();
1962 ///
1963 ///     // execution never gets here
1964 /// }
1965 /// ```
1966 ///
1967 /// The `abort` function terminates the process, so the destructor will not
1968 /// get run on the example below:
1969 ///
1970 /// ```no_run
1971 /// use std::process;
1972 ///
1973 /// struct HasDrop;
1974 ///
1975 /// impl Drop for HasDrop {
1976 ///     fn drop(&mut self) {
1977 ///         println!("This will never be printed!");
1978 ///     }
1979 /// }
1980 ///
1981 /// fn main() {
1982 ///     let _x = HasDrop;
1983 ///     process::abort();
1984 ///     // the destructor implemented for HasDrop will never get run
1985 /// }
1986 /// ```
1987 ///
1988 /// [panic hook]: crate::panic::set_hook
1989 #[stable(feature = "process_abort", since = "1.17.0")]
1990 #[cold]
1991 pub fn abort() -> ! {
1992     crate::sys::abort_internal();
1993 }
1994
1995 /// Returns the OS-assigned process identifier associated with this process.
1996 ///
1997 /// # Examples
1998 ///
1999 /// Basic usage:
2000 ///
2001 /// ```no_run
2002 /// use std::process;
2003 ///
2004 /// println!("My pid is {}", process::id());
2005 /// ```
2006 ///
2007 ///
2008 #[must_use]
2009 #[stable(feature = "getpid", since = "1.26.0")]
2010 pub fn id() -> u32 {
2011     crate::sys::os::getpid()
2012 }
2013
2014 /// A trait for implementing arbitrary return types in the `main` function.
2015 ///
2016 /// The C-main function only supports to return integers as return type.
2017 /// So, every type implementing the `Termination` trait has to be converted
2018 /// to an integer.
2019 ///
2020 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2021 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2022 #[cfg_attr(not(test), lang = "termination")]
2023 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2024 #[rustc_on_unimplemented(
2025     message = "`main` has invalid return type `{Self}`",
2026     label = "`main` can only return types that implement `{Termination}`"
2027 )]
2028 pub trait Termination {
2029     /// Is called to get the representation of the value as status code.
2030     /// This status code is returned to the operating system.
2031     fn report(self) -> i32;
2032 }
2033
2034 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2035 impl Termination for () {
2036     #[inline]
2037     fn report(self) -> i32 {
2038         ExitCode::SUCCESS.report()
2039     }
2040 }
2041
2042 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2043 impl<E: fmt::Debug> Termination for Result<(), E> {
2044     fn report(self) -> i32 {
2045         match self {
2046             Ok(()) => ().report(),
2047             Err(err) => Err::<!, _>(err).report(),
2048         }
2049     }
2050 }
2051
2052 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2053 impl Termination for ! {
2054     fn report(self) -> i32 {
2055         self
2056     }
2057 }
2058
2059 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2060 impl<E: fmt::Debug> Termination for Result<!, E> {
2061     fn report(self) -> i32 {
2062         let Err(err) = self;
2063         eprintln!("Error: {:?}", err);
2064         ExitCode::FAILURE.report()
2065     }
2066 }
2067
2068 #[unstable(feature = "termination_trait_lib", issue = "43301")]
2069 impl Termination for ExitCode {
2070     #[inline]
2071     fn report(self) -> i32 {
2072         self.0.as_i32()
2073     }
2074 }