std/
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//! # Windows argument splitting
92//!
93//! On Unix systems arguments are passed to a new process as an array of strings,
94//! but on Windows arguments are passed as a single commandline string and it is
95//! up to the child process to parse it into an array. Therefore the parent and
96//! child processes must agree on how the commandline string is encoded.
97//!
98//! Most programs use the standard C run-time `argv`, which in practice results
99//! in consistent argument handling. However, some programs have their own way of
100//! parsing the commandline string. In these cases using [`arg`] or [`args`] may
101//! result in the child process seeing a different array of arguments than the
102//! parent process intended.
103//!
104//! Two ways of mitigating this are:
105//!
106//! * Validate untrusted input so that only a safe subset is allowed.
107//! * Use [`raw_arg`] to build a custom commandline. This bypasses the escaping
108//!   rules used by [`arg`] so should be used with due caution.
109//!
110//! `cmd.exe` and `.bat` files use non-standard argument parsing and are especially
111//! vulnerable to malicious input as they may be used to run arbitrary shell
112//! commands. Untrusted arguments should be restricted as much as possible.
113//! For examples on handling this see [`raw_arg`].
114//!
115//! ### Batch file special handling
116//!
117//! On Windows, `Command` uses the Windows API function [`CreateProcessW`] to
118//! spawn new processes. An undocumented feature of this function is that
119//! when given a `.bat` file as the application to run, it will automatically
120//! convert that into running `cmd.exe /c` with the batch file as the next argument.
121//!
122//! For historical reasons Rust currently preserves this behavior when using
123//! [`Command::new`], and escapes the arguments according to `cmd.exe` rules.
124//! Due to the complexity of `cmd.exe` argument handling, it might not be
125//! possible to safely escape some special characters, and using them will result
126//! in an error being returned at process spawn. The set of unescapeable
127//! special characters might change between releases.
128//!
129//! Also note that running batch scripts in this way may be removed in the
130//! future and so should not be relied upon.
131//!
132//! [`spawn`]: Command::spawn
133//! [`output`]: Command::output
134//!
135//! [`stdout`]: Command::stdout
136//! [`stdin`]: Command::stdin
137//! [`stderr`]: Command::stderr
138//!
139//! [`Write`]: io::Write
140//! [`Read`]: io::Read
141//!
142//! [`arg`]: Command::arg
143//! [`args`]: Command::args
144//! [`raw_arg`]: crate::os::windows::process::CommandExt::raw_arg
145//!
146//! [`CreateProcessW`]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
147
148#![stable(feature = "process", since = "1.0.0")]
149#![deny(unsafe_op_in_unsafe_fn)]
150
151#[cfg(all(
152    test,
153    not(any(
154        target_os = "none",
155        target_os = "emscripten",
156        target_os = "wasi",
157        target_env = "sgx",
158        target_os = "xous",
159        target_os = "trusty",
160    ))
161))]
162mod tests;
163
164use crate::convert::Infallible;
165use crate::ffi::OsStr;
166use crate::io::prelude::*;
167use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
168use crate::num::NonZero;
169use crate::path::Path;
170use crate::sys::pipe::{AnonPipe, read2};
171use crate::sys::process as imp;
172use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
173use crate::{fmt, fs, str};
174
175/// Representation of a running or exited child process.
176///
177/// This structure is used to represent and manage child processes. A child
178/// process is created via the [`Command`] struct, which configures the
179/// spawning process and can itself be constructed using a builder-style
180/// interface.
181///
182/// There is no implementation of [`Drop`] for child processes,
183/// so if you do not ensure the `Child` has exited then it will continue to
184/// run, even after the `Child` handle to the child process has gone out of
185/// scope.
186///
187/// Calling [`wait`] (or other functions that wrap around it) will make
188/// the parent process wait until the child has actually exited before
189/// continuing.
190///
191/// # Warning
192///
193/// On some systems, calling [`wait`] or similar is necessary for the OS to
194/// release resources. A process that terminated but has not been waited on is
195/// still around as a "zombie". Leaving too many zombies around may exhaust
196/// global resources (for example process IDs).
197///
198/// The standard library does *not* automatically wait on child processes (not
199/// even if the `Child` is dropped), it is up to the application developer to do
200/// so. As a consequence, dropping `Child` handles without waiting on them first
201/// is not recommended in long-running applications.
202///
203/// # Examples
204///
205/// ```should_panic
206/// use std::process::Command;
207///
208/// let mut child = Command::new("/bin/cat")
209///     .arg("file.txt")
210///     .spawn()
211///     .expect("failed to execute child");
212///
213/// let ecode = child.wait().expect("failed to wait on child");
214///
215/// assert!(ecode.success());
216/// ```
217///
218/// [`wait`]: Child::wait
219#[stable(feature = "process", since = "1.0.0")]
220#[cfg_attr(not(test), rustc_diagnostic_item = "Child")]
221pub struct Child {
222    pub(crate) handle: imp::Process,
223
224    /// The handle for writing to the child's standard input (stdin), if it
225    /// has been captured. You might find it helpful to do
226    ///
227    /// ```ignore (incomplete)
228    /// let stdin = child.stdin.take().expect("handle present");
229    /// ```
230    ///
231    /// to avoid partially moving the `child` and thus blocking yourself from calling
232    /// functions on `child` while using `stdin`.
233    #[stable(feature = "process", since = "1.0.0")]
234    pub stdin: Option<ChildStdin>,
235
236    /// The handle for reading from the child's standard output (stdout), if it
237    /// has been captured. You might find it helpful to do
238    ///
239    /// ```ignore (incomplete)
240    /// let stdout = child.stdout.take().expect("handle present");
241    /// ```
242    ///
243    /// to avoid partially moving the `child` and thus blocking yourself from calling
244    /// functions on `child` while using `stdout`.
245    #[stable(feature = "process", since = "1.0.0")]
246    pub stdout: Option<ChildStdout>,
247
248    /// The handle for reading from the child's standard error (stderr), if it
249    /// has been captured. You might find it helpful to do
250    ///
251    /// ```ignore (incomplete)
252    /// let stderr = child.stderr.take().expect("handle present");
253    /// ```
254    ///
255    /// to avoid partially moving the `child` and thus blocking yourself from calling
256    /// functions on `child` while using `stderr`.
257    #[stable(feature = "process", since = "1.0.0")]
258    pub stderr: Option<ChildStderr>,
259}
260
261/// Allows extension traits within `std`.
262#[unstable(feature = "sealed", issue = "none")]
263impl crate::sealed::Sealed for Child {}
264
265impl AsInner<imp::Process> for Child {
266    #[inline]
267    fn as_inner(&self) -> &imp::Process {
268        &self.handle
269    }
270}
271
272impl FromInner<(imp::Process, StdioPipes)> for Child {
273    fn from_inner((handle, io): (imp::Process, StdioPipes)) -> Child {
274        Child {
275            handle,
276            stdin: io.stdin.map(ChildStdin::from_inner),
277            stdout: io.stdout.map(ChildStdout::from_inner),
278            stderr: io.stderr.map(ChildStderr::from_inner),
279        }
280    }
281}
282
283impl IntoInner<imp::Process> for Child {
284    fn into_inner(self) -> imp::Process {
285        self.handle
286    }
287}
288
289#[stable(feature = "std_debug", since = "1.16.0")]
290impl fmt::Debug for Child {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        f.debug_struct("Child")
293            .field("stdin", &self.stdin)
294            .field("stdout", &self.stdout)
295            .field("stderr", &self.stderr)
296            .finish_non_exhaustive()
297    }
298}
299
300/// The pipes connected to a spawned process.
301///
302/// Used to pass pipe handles between this module and [`imp`].
303pub(crate) struct StdioPipes {
304    pub stdin: Option<AnonPipe>,
305    pub stdout: Option<AnonPipe>,
306    pub stderr: Option<AnonPipe>,
307}
308
309/// A handle to a child process's standard input (stdin).
310///
311/// This struct is used in the [`stdin`] field on [`Child`].
312///
313/// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
314/// file handle will be closed. If the child process was blocked on input prior
315/// to being dropped, it will become unblocked after dropping.
316///
317/// [`stdin`]: Child::stdin
318/// [dropped]: Drop
319#[stable(feature = "process", since = "1.0.0")]
320pub struct ChildStdin {
321    inner: AnonPipe,
322}
323
324// In addition to the `impl`s here, `ChildStdin` also has `impl`s for
325// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
326// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
327// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
328// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
329
330#[stable(feature = "process", since = "1.0.0")]
331impl Write for ChildStdin {
332    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
333        (&*self).write(buf)
334    }
335
336    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
337        (&*self).write_vectored(bufs)
338    }
339
340    fn is_write_vectored(&self) -> bool {
341        io::Write::is_write_vectored(&&*self)
342    }
343
344    #[inline]
345    fn flush(&mut self) -> io::Result<()> {
346        (&*self).flush()
347    }
348}
349
350#[stable(feature = "write_mt", since = "1.48.0")]
351impl Write for &ChildStdin {
352    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
353        self.inner.write(buf)
354    }
355
356    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
357        self.inner.write_vectored(bufs)
358    }
359
360    fn is_write_vectored(&self) -> bool {
361        self.inner.is_write_vectored()
362    }
363
364    #[inline]
365    fn flush(&mut self) -> io::Result<()> {
366        Ok(())
367    }
368}
369
370impl AsInner<AnonPipe> for ChildStdin {
371    #[inline]
372    fn as_inner(&self) -> &AnonPipe {
373        &self.inner
374    }
375}
376
377impl IntoInner<AnonPipe> for ChildStdin {
378    fn into_inner(self) -> AnonPipe {
379        self.inner
380    }
381}
382
383impl FromInner<AnonPipe> for ChildStdin {
384    fn from_inner(pipe: AnonPipe) -> ChildStdin {
385        ChildStdin { inner: pipe }
386    }
387}
388
389#[stable(feature = "std_debug", since = "1.16.0")]
390impl fmt::Debug for ChildStdin {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        f.debug_struct("ChildStdin").finish_non_exhaustive()
393    }
394}
395
396/// A handle to a child process's standard output (stdout).
397///
398/// This struct is used in the [`stdout`] field on [`Child`].
399///
400/// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
401/// underlying file handle will be closed.
402///
403/// [`stdout`]: Child::stdout
404/// [dropped]: Drop
405#[stable(feature = "process", since = "1.0.0")]
406pub struct ChildStdout {
407    inner: AnonPipe,
408}
409
410// In addition to the `impl`s here, `ChildStdout` also has `impl`s for
411// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
412// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
413// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
414// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
415
416#[stable(feature = "process", since = "1.0.0")]
417impl Read for ChildStdout {
418    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
419        self.inner.read(buf)
420    }
421
422    fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
423        self.inner.read_buf(buf)
424    }
425
426    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
427        self.inner.read_vectored(bufs)
428    }
429
430    #[inline]
431    fn is_read_vectored(&self) -> bool {
432        self.inner.is_read_vectored()
433    }
434
435    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
436        self.inner.read_to_end(buf)
437    }
438}
439
440impl AsInner<AnonPipe> for ChildStdout {
441    #[inline]
442    fn as_inner(&self) -> &AnonPipe {
443        &self.inner
444    }
445}
446
447impl IntoInner<AnonPipe> for ChildStdout {
448    fn into_inner(self) -> AnonPipe {
449        self.inner
450    }
451}
452
453impl FromInner<AnonPipe> for ChildStdout {
454    fn from_inner(pipe: AnonPipe) -> ChildStdout {
455        ChildStdout { inner: pipe }
456    }
457}
458
459#[stable(feature = "std_debug", since = "1.16.0")]
460impl fmt::Debug for ChildStdout {
461    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
462        f.debug_struct("ChildStdout").finish_non_exhaustive()
463    }
464}
465
466/// A handle to a child process's stderr.
467///
468/// This struct is used in the [`stderr`] field on [`Child`].
469///
470/// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
471/// underlying file handle will be closed.
472///
473/// [`stderr`]: Child::stderr
474/// [dropped]: Drop
475#[stable(feature = "process", since = "1.0.0")]
476pub struct ChildStderr {
477    inner: AnonPipe,
478}
479
480// In addition to the `impl`s here, `ChildStderr` also has `impl`s for
481// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
482// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
483// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
484// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
485
486#[stable(feature = "process", since = "1.0.0")]
487impl Read for ChildStderr {
488    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
489        self.inner.read(buf)
490    }
491
492    fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
493        self.inner.read_buf(buf)
494    }
495
496    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
497        self.inner.read_vectored(bufs)
498    }
499
500    #[inline]
501    fn is_read_vectored(&self) -> bool {
502        self.inner.is_read_vectored()
503    }
504
505    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
506        self.inner.read_to_end(buf)
507    }
508}
509
510impl AsInner<AnonPipe> for ChildStderr {
511    #[inline]
512    fn as_inner(&self) -> &AnonPipe {
513        &self.inner
514    }
515}
516
517impl IntoInner<AnonPipe> for ChildStderr {
518    fn into_inner(self) -> AnonPipe {
519        self.inner
520    }
521}
522
523impl FromInner<AnonPipe> for ChildStderr {
524    fn from_inner(pipe: AnonPipe) -> ChildStderr {
525        ChildStderr { inner: pipe }
526    }
527}
528
529#[stable(feature = "std_debug", since = "1.16.0")]
530impl fmt::Debug for ChildStderr {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        f.debug_struct("ChildStderr").finish_non_exhaustive()
533    }
534}
535
536/// A process builder, providing fine-grained control
537/// over how a new process should be spawned.
538///
539/// A default configuration can be
540/// generated using `Command::new(program)`, where `program` gives a path to the
541/// program to be executed. Additional builder methods allow the configuration
542/// to be changed (for example, by adding arguments) prior to spawning:
543///
544/// ```
545/// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
546/// # // required by `Command`.
547/// # if cfg!(not(any(
548/// #     target_os = "vxworks",
549/// #     all(target_vendor = "apple", not(target_os = "macos"))
550/// # ))) {
551/// use std::process::Command;
552///
553/// let output = if cfg!(target_os = "windows") {
554///     Command::new("cmd")
555///         .args(["/C", "echo hello"])
556///         .output()
557///         .expect("failed to execute process")
558/// } else {
559///     Command::new("sh")
560///         .arg("-c")
561///         .arg("echo hello")
562///         .output()
563///         .expect("failed to execute process")
564/// };
565///
566/// let hello = output.stdout;
567/// # }
568/// ```
569///
570/// `Command` can be reused to spawn multiple processes. The builder methods
571/// change the command without needing to immediately spawn the process.
572///
573/// ```no_run
574/// use std::process::Command;
575///
576/// let mut echo_hello = Command::new("sh");
577/// echo_hello.arg("-c").arg("echo hello");
578/// let hello_1 = echo_hello.output().expect("failed to execute process");
579/// let hello_2 = echo_hello.output().expect("failed to execute process");
580/// ```
581///
582/// Similarly, you can call builder methods after spawning a process and then
583/// spawn a new process with the modified settings.
584///
585/// ```no_run
586/// use std::process::Command;
587///
588/// let mut list_dir = Command::new("ls");
589///
590/// // Execute `ls` in the current directory of the program.
591/// list_dir.status().expect("process failed to execute");
592///
593/// println!();
594///
595/// // Change `ls` to execute in the root directory.
596/// list_dir.current_dir("/");
597///
598/// // And then execute `ls` again but in the root directory.
599/// list_dir.status().expect("process failed to execute");
600/// ```
601#[stable(feature = "process", since = "1.0.0")]
602#[cfg_attr(not(test), rustc_diagnostic_item = "Command")]
603pub struct Command {
604    inner: imp::Command,
605}
606
607/// Allows extension traits within `std`.
608#[unstable(feature = "sealed", issue = "none")]
609impl crate::sealed::Sealed for Command {}
610
611impl Command {
612    /// Constructs a new `Command` for launching the program at
613    /// path `program`, with the following default configuration:
614    ///
615    /// * No arguments to the program
616    /// * Inherit the current process's environment
617    /// * Inherit the current process's working directory
618    /// * Inherit stdin/stdout/stderr for [`spawn`] or [`status`], but create pipes for [`output`]
619    ///
620    /// [`spawn`]: Self::spawn
621    /// [`status`]: Self::status
622    /// [`output`]: Self::output
623    ///
624    /// Builder methods are provided to change these defaults and
625    /// otherwise configure the process.
626    ///
627    /// If `program` is not an absolute path, the `PATH` will be searched in
628    /// an OS-defined way.
629    ///
630    /// The search path to be used may be controlled by setting the
631    /// `PATH` environment variable on the Command,
632    /// but this has some implementation limitations on Windows
633    /// (see issue #37519).
634    ///
635    /// # Platform-specific behavior
636    ///
637    /// Note on Windows: For executable files with the .exe extension,
638    /// it can be omitted when specifying the program for this Command.
639    /// However, if the file has a different extension,
640    /// a filename including the extension needs to be provided,
641    /// otherwise the file won't be found.
642    ///
643    /// # Examples
644    ///
645    /// ```no_run
646    /// use std::process::Command;
647    ///
648    /// Command::new("sh")
649    ///     .spawn()
650    ///     .expect("sh command failed to start");
651    /// ```
652    ///
653    /// # Caveats
654    ///
655    /// [`Command::new`] is only intended to accept the path of the program. If you pass a program
656    /// path along with arguments like `Command::new("ls -l").spawn()`, it will try to search for
657    /// `ls -l` literally. The arguments need to be passed separately, such as via [`arg`] or
658    /// [`args`].
659    ///
660    /// ```no_run
661    /// use std::process::Command;
662    ///
663    /// Command::new("ls")
664    ///     .arg("-l") // arg passed separately
665    ///     .spawn()
666    ///     .expect("ls command failed to start");
667    /// ```
668    ///
669    /// [`arg`]: Self::arg
670    /// [`args`]: Self::args
671    #[stable(feature = "process", since = "1.0.0")]
672    pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
673        Command { inner: imp::Command::new(program.as_ref()) }
674    }
675
676    /// Adds an argument to pass to the program.
677    ///
678    /// Only one argument can be passed per use. So instead of:
679    ///
680    /// ```no_run
681    /// # std::process::Command::new("sh")
682    /// .arg("-C /path/to/repo")
683    /// # ;
684    /// ```
685    ///
686    /// usage would be:
687    ///
688    /// ```no_run
689    /// # std::process::Command::new("sh")
690    /// .arg("-C")
691    /// .arg("/path/to/repo")
692    /// # ;
693    /// ```
694    ///
695    /// To pass multiple arguments see [`args`].
696    ///
697    /// [`args`]: Command::args
698    ///
699    /// Note that the argument is not passed through a shell, but given
700    /// literally to the program. This means that shell syntax like quotes,
701    /// escaped characters, word splitting, glob patterns, variable substitution,
702    /// etc. have no effect.
703    ///
704    /// <div class="warning">
705    ///
706    /// On Windows, use caution with untrusted inputs. Most applications use the
707    /// standard convention for decoding arguments passed to them. These are safe to
708    /// use with `arg`. However, some applications such as `cmd.exe` and `.bat` files
709    /// use a non-standard way of decoding arguments. They are therefore vulnerable
710    /// to malicious input.
711    ///
712    /// In the case of `cmd.exe` this is especially important because a malicious
713    /// argument can potentially run arbitrary shell commands.
714    ///
715    /// See [Windows argument splitting][windows-args] for more details
716    /// or [`raw_arg`] for manually implementing non-standard argument encoding.
717    ///
718    /// [`raw_arg`]: crate::os::windows::process::CommandExt::raw_arg
719    /// [windows-args]: crate::process#windows-argument-splitting
720    ///
721    /// </div>
722    ///
723    /// # Examples
724    ///
725    /// ```no_run
726    /// use std::process::Command;
727    ///
728    /// Command::new("ls")
729    ///     .arg("-l")
730    ///     .arg("-a")
731    ///     .spawn()
732    ///     .expect("ls command failed to start");
733    /// ```
734    #[stable(feature = "process", since = "1.0.0")]
735    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
736        self.inner.arg(arg.as_ref());
737        self
738    }
739
740    /// Adds multiple arguments to pass to the program.
741    ///
742    /// To pass a single argument see [`arg`].
743    ///
744    /// [`arg`]: Command::arg
745    ///
746    /// Note that the arguments are not passed through a shell, but given
747    /// literally to the program. This means that shell syntax like quotes,
748    /// escaped characters, word splitting, glob patterns, variable substitution, etc.
749    /// have no effect.
750    ///
751    /// <div class="warning">
752    ///
753    /// On Windows, use caution with untrusted inputs. Most applications use the
754    /// standard convention for decoding arguments passed to them. These are safe to
755    /// use with `arg`. However, some applications such as `cmd.exe` and `.bat` files
756    /// use a non-standard way of decoding arguments. They are therefore vulnerable
757    /// to malicious input.
758    ///
759    /// In the case of `cmd.exe` this is especially important because a malicious
760    /// argument can potentially run arbitrary shell commands.
761    ///
762    /// See [Windows argument splitting][windows-args] for more details
763    /// or [`raw_arg`] for manually implementing non-standard argument encoding.
764    ///
765    /// [`raw_arg`]: crate::os::windows::process::CommandExt::raw_arg
766    /// [windows-args]: crate::process#windows-argument-splitting
767    ///
768    /// </div>
769    ///
770    /// # Examples
771    ///
772    /// ```no_run
773    /// use std::process::Command;
774    ///
775    /// Command::new("ls")
776    ///     .args(["-l", "-a"])
777    ///     .spawn()
778    ///     .expect("ls command failed to start");
779    /// ```
780    #[stable(feature = "process", since = "1.0.0")]
781    pub fn args<I, S>(&mut self, args: I) -> &mut Command
782    where
783        I: IntoIterator<Item = S>,
784        S: AsRef<OsStr>,
785    {
786        for arg in args {
787            self.arg(arg.as_ref());
788        }
789        self
790    }
791
792    /// Inserts or updates an explicit environment variable mapping.
793    ///
794    /// This method allows you to add an environment variable mapping to the spawned process or
795    /// overwrite a previously set value. You can use [`Command::envs`] to set multiple environment
796    /// variables simultaneously.
797    ///
798    /// Child processes will inherit environment variables from their parent process by default.
799    /// Environment variables explicitly set using [`Command::env`] take precedence over inherited
800    /// variables. You can disable environment variable inheritance entirely using
801    /// [`Command::env_clear`] or for a single key using [`Command::env_remove`].
802    ///
803    /// Note that environment variable names are case-insensitive (but
804    /// case-preserving) on Windows and case-sensitive on all other platforms.
805    ///
806    /// # Examples
807    ///
808    /// ```no_run
809    /// use std::process::Command;
810    ///
811    /// Command::new("ls")
812    ///     .env("PATH", "/bin")
813    ///     .spawn()
814    ///     .expect("ls command failed to start");
815    /// ```
816    #[stable(feature = "process", since = "1.0.0")]
817    pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
818    where
819        K: AsRef<OsStr>,
820        V: AsRef<OsStr>,
821    {
822        self.inner.env_mut().set(key.as_ref(), val.as_ref());
823        self
824    }
825
826    /// Inserts or updates multiple explicit environment variable mappings.
827    ///
828    /// This method allows you to add multiple environment variable mappings to the spawned process
829    /// or overwrite previously set values. You can use [`Command::env`] to set a single environment
830    /// variable.
831    ///
832    /// Child processes will inherit environment variables from their parent process by default.
833    /// Environment variables explicitly set using [`Command::envs`] take precedence over inherited
834    /// variables. You can disable environment variable inheritance entirely using
835    /// [`Command::env_clear`] or for a single key using [`Command::env_remove`].
836    ///
837    /// Note that environment variable names are case-insensitive (but case-preserving) on Windows
838    /// and case-sensitive on all other platforms.
839    ///
840    /// # Examples
841    ///
842    /// ```no_run
843    /// use std::process::{Command, Stdio};
844    /// use std::env;
845    /// use std::collections::HashMap;
846    ///
847    /// let filtered_env : HashMap<String, String> =
848    ///     env::vars().filter(|&(ref k, _)|
849    ///         k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
850    ///     ).collect();
851    ///
852    /// Command::new("printenv")
853    ///     .stdin(Stdio::null())
854    ///     .stdout(Stdio::inherit())
855    ///     .env_clear()
856    ///     .envs(&filtered_env)
857    ///     .spawn()
858    ///     .expect("printenv failed to start");
859    /// ```
860    #[stable(feature = "command_envs", since = "1.19.0")]
861    pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
862    where
863        I: IntoIterator<Item = (K, V)>,
864        K: AsRef<OsStr>,
865        V: AsRef<OsStr>,
866    {
867        for (ref key, ref val) in vars {
868            self.inner.env_mut().set(key.as_ref(), val.as_ref());
869        }
870        self
871    }
872
873    /// Removes an explicitly set environment variable and prevents inheriting it from a parent
874    /// process.
875    ///
876    /// This method will remove the explicit value of an environment variable set via
877    /// [`Command::env`] or [`Command::envs`]. In addition, it will prevent the spawned child
878    /// process from inheriting that environment variable from its parent process.
879    ///
880    /// After calling [`Command::env_remove`], the value associated with its key from
881    /// [`Command::get_envs`] will be [`None`].
882    ///
883    /// To clear all explicitly set environment variables and disable all environment variable
884    /// inheritance, you can use [`Command::env_clear`].
885    ///
886    /// # Examples
887    ///
888    /// Prevent any inherited `GIT_DIR` variable from changing the target of the `git` command,
889    /// while allowing all other variables, like `GIT_AUTHOR_NAME`.
890    ///
891    /// ```no_run
892    /// use std::process::Command;
893    ///
894    /// Command::new("git")
895    ///     .arg("commit")
896    ///     .env_remove("GIT_DIR")
897    ///     .spawn()?;
898    /// # std::io::Result::Ok(())
899    /// ```
900    #[stable(feature = "process", since = "1.0.0")]
901    pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
902        self.inner.env_mut().remove(key.as_ref());
903        self
904    }
905
906    /// Clears all explicitly set environment variables and prevents inheriting any parent process
907    /// environment variables.
908    ///
909    /// This method will remove all explicitly added environment variables set via [`Command::env`]
910    /// or [`Command::envs`]. In addition, it will prevent the spawned child process from inheriting
911    /// any environment variable from its parent process.
912    ///
913    /// After calling [`Command::env_clear`], the iterator from [`Command::get_envs`] will be
914    /// empty.
915    ///
916    /// You can use [`Command::env_remove`] to clear a single mapping.
917    ///
918    /// # Examples
919    ///
920    /// The behavior of `sort` is affected by `LANG` and `LC_*` environment variables.
921    /// Clearing the environment makes `sort`'s behavior independent of the parent processes' language.
922    ///
923    /// ```no_run
924    /// use std::process::Command;
925    ///
926    /// Command::new("sort")
927    ///     .arg("file.txt")
928    ///     .env_clear()
929    ///     .spawn()?;
930    /// # std::io::Result::Ok(())
931    /// ```
932    #[stable(feature = "process", since = "1.0.0")]
933    pub fn env_clear(&mut self) -> &mut Command {
934        self.inner.env_mut().clear();
935        self
936    }
937
938    /// Sets the working directory for the child process.
939    ///
940    /// # Platform-specific behavior
941    ///
942    /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
943    /// whether it should be interpreted relative to the parent's working
944    /// directory or relative to `current_dir`. The behavior in this case is
945    /// platform specific and unstable, and it's recommended to use
946    /// [`canonicalize`] to get an absolute program path instead.
947    ///
948    /// # Examples
949    ///
950    /// ```no_run
951    /// use std::process::Command;
952    ///
953    /// Command::new("ls")
954    ///     .current_dir("/bin")
955    ///     .spawn()
956    ///     .expect("ls command failed to start");
957    /// ```
958    ///
959    /// [`canonicalize`]: crate::fs::canonicalize
960    #[stable(feature = "process", since = "1.0.0")]
961    pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
962        self.inner.cwd(dir.as_ref().as_ref());
963        self
964    }
965
966    /// Configuration for the child process's standard input (stdin) handle.
967    ///
968    /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
969    /// defaults to [`piped`] when used with [`output`].
970    ///
971    /// [`inherit`]: Stdio::inherit
972    /// [`piped`]: Stdio::piped
973    /// [`spawn`]: Self::spawn
974    /// [`status`]: Self::status
975    /// [`output`]: Self::output
976    ///
977    /// # Examples
978    ///
979    /// ```no_run
980    /// use std::process::{Command, Stdio};
981    ///
982    /// Command::new("ls")
983    ///     .stdin(Stdio::null())
984    ///     .spawn()
985    ///     .expect("ls command failed to start");
986    /// ```
987    #[stable(feature = "process", since = "1.0.0")]
988    pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
989        self.inner.stdin(cfg.into().0);
990        self
991    }
992
993    /// Configuration for the child process's standard output (stdout) handle.
994    ///
995    /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
996    /// defaults to [`piped`] when used with [`output`].
997    ///
998    /// [`inherit`]: Stdio::inherit
999    /// [`piped`]: Stdio::piped
1000    /// [`spawn`]: Self::spawn
1001    /// [`status`]: Self::status
1002    /// [`output`]: Self::output
1003    ///
1004    /// # Examples
1005    ///
1006    /// ```no_run
1007    /// use std::process::{Command, Stdio};
1008    ///
1009    /// Command::new("ls")
1010    ///     .stdout(Stdio::null())
1011    ///     .spawn()
1012    ///     .expect("ls command failed to start");
1013    /// ```
1014    #[stable(feature = "process", since = "1.0.0")]
1015    pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
1016        self.inner.stdout(cfg.into().0);
1017        self
1018    }
1019
1020    /// Configuration for the child process's standard error (stderr) handle.
1021    ///
1022    /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
1023    /// defaults to [`piped`] when used with [`output`].
1024    ///
1025    /// [`inherit`]: Stdio::inherit
1026    /// [`piped`]: Stdio::piped
1027    /// [`spawn`]: Self::spawn
1028    /// [`status`]: Self::status
1029    /// [`output`]: Self::output
1030    ///
1031    /// # Examples
1032    ///
1033    /// ```no_run
1034    /// use std::process::{Command, Stdio};
1035    ///
1036    /// Command::new("ls")
1037    ///     .stderr(Stdio::null())
1038    ///     .spawn()
1039    ///     .expect("ls command failed to start");
1040    /// ```
1041    #[stable(feature = "process", since = "1.0.0")]
1042    pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
1043        self.inner.stderr(cfg.into().0);
1044        self
1045    }
1046
1047    /// Executes the command as a child process, returning a handle to it.
1048    ///
1049    /// By default, stdin, stdout and stderr are inherited from the parent.
1050    ///
1051    /// # Examples
1052    ///
1053    /// ```no_run
1054    /// use std::process::Command;
1055    ///
1056    /// Command::new("ls")
1057    ///     .spawn()
1058    ///     .expect("ls command failed to start");
1059    /// ```
1060    #[stable(feature = "process", since = "1.0.0")]
1061    pub fn spawn(&mut self) -> io::Result<Child> {
1062        self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
1063    }
1064
1065    /// Executes the command as a child process, waiting for it to finish and
1066    /// collecting all of its output.
1067    ///
1068    /// By default, stdout and stderr are captured (and used to provide the
1069    /// resulting output). Stdin is not inherited from the parent and any
1070    /// attempt by the child process to read from the stdin stream will result
1071    /// in the stream immediately closing.
1072    ///
1073    /// # Examples
1074    ///
1075    /// ```should_panic
1076    /// use std::process::Command;
1077    /// use std::io::{self, Write};
1078    /// let output = Command::new("/bin/cat")
1079    ///     .arg("file.txt")
1080    ///     .output()?;
1081    ///
1082    /// println!("status: {}", output.status);
1083    /// io::stdout().write_all(&output.stdout)?;
1084    /// io::stderr().write_all(&output.stderr)?;
1085    ///
1086    /// assert!(output.status.success());
1087    /// # io::Result::Ok(())
1088    /// ```
1089    #[stable(feature = "process", since = "1.0.0")]
1090    pub fn output(&mut self) -> io::Result<Output> {
1091        let (status, stdout, stderr) = imp::output(&mut self.inner)?;
1092        Ok(Output { status: ExitStatus(status), stdout, stderr })
1093    }
1094
1095    /// Executes a command as a child process, waiting for it to finish and
1096    /// collecting its status.
1097    ///
1098    /// By default, stdin, stdout and stderr are inherited from the parent.
1099    ///
1100    /// # Examples
1101    ///
1102    /// ```should_panic
1103    /// use std::process::Command;
1104    ///
1105    /// let status = Command::new("/bin/cat")
1106    ///     .arg("file.txt")
1107    ///     .status()
1108    ///     .expect("failed to execute process");
1109    ///
1110    /// println!("process finished with: {status}");
1111    ///
1112    /// assert!(status.success());
1113    /// ```
1114    #[stable(feature = "process", since = "1.0.0")]
1115    pub fn status(&mut self) -> io::Result<ExitStatus> {
1116        self.inner
1117            .spawn(imp::Stdio::Inherit, true)
1118            .map(Child::from_inner)
1119            .and_then(|mut p| p.wait())
1120    }
1121
1122    /// Returns the path to the program that was given to [`Command::new`].
1123    ///
1124    /// # Examples
1125    ///
1126    /// ```
1127    /// use std::process::Command;
1128    ///
1129    /// let cmd = Command::new("echo");
1130    /// assert_eq!(cmd.get_program(), "echo");
1131    /// ```
1132    #[must_use]
1133    #[stable(feature = "command_access", since = "1.57.0")]
1134    pub fn get_program(&self) -> &OsStr {
1135        self.inner.get_program()
1136    }
1137
1138    /// Returns an iterator of the arguments that will be passed to the program.
1139    ///
1140    /// This does not include the path to the program as the first argument;
1141    /// it only includes the arguments specified with [`Command::arg`] and
1142    /// [`Command::args`].
1143    ///
1144    /// # Examples
1145    ///
1146    /// ```
1147    /// use std::ffi::OsStr;
1148    /// use std::process::Command;
1149    ///
1150    /// let mut cmd = Command::new("echo");
1151    /// cmd.arg("first").arg("second");
1152    /// let args: Vec<&OsStr> = cmd.get_args().collect();
1153    /// assert_eq!(args, &["first", "second"]);
1154    /// ```
1155    #[stable(feature = "command_access", since = "1.57.0")]
1156    pub fn get_args(&self) -> CommandArgs<'_> {
1157        CommandArgs { inner: self.inner.get_args() }
1158    }
1159
1160    /// Returns an iterator of the environment variables explicitly set for the child process.
1161    ///
1162    /// Environment variables explicitly set using [`Command::env`], [`Command::envs`], and
1163    /// [`Command::env_remove`] can be retrieved with this method.
1164    ///
1165    /// Note that this output does not include environment variables inherited from the parent
1166    /// process.
1167    ///
1168    /// Each element is a tuple key/value pair `(&OsStr, Option<&OsStr>)`. A [`None`] value
1169    /// indicates its key was explicitly removed via [`Command::env_remove`]. The associated key for
1170    /// the [`None`] value will no longer inherit from its parent process.
1171    ///
1172    /// An empty iterator can indicate that no explicit mappings were added or that
1173    /// [`Command::env_clear`] was called. After calling [`Command::env_clear`], the child process
1174    /// will not inherit any environment variables from its parent process.
1175    ///
1176    /// # Examples
1177    ///
1178    /// ```
1179    /// use std::ffi::OsStr;
1180    /// use std::process::Command;
1181    ///
1182    /// let mut cmd = Command::new("ls");
1183    /// cmd.env("TERM", "dumb").env_remove("TZ");
1184    /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1185    /// assert_eq!(envs, &[
1186    ///     (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1187    ///     (OsStr::new("TZ"), None)
1188    /// ]);
1189    /// ```
1190    #[stable(feature = "command_access", since = "1.57.0")]
1191    pub fn get_envs(&self) -> CommandEnvs<'_> {
1192        CommandEnvs { iter: self.inner.get_envs() }
1193    }
1194
1195    /// Returns the working directory for the child process.
1196    ///
1197    /// This returns [`None`] if the working directory will not be changed.
1198    ///
1199    /// # Examples
1200    ///
1201    /// ```
1202    /// use std::path::Path;
1203    /// use std::process::Command;
1204    ///
1205    /// let mut cmd = Command::new("ls");
1206    /// assert_eq!(cmd.get_current_dir(), None);
1207    /// cmd.current_dir("/bin");
1208    /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1209    /// ```
1210    #[must_use]
1211    #[stable(feature = "command_access", since = "1.57.0")]
1212    pub fn get_current_dir(&self) -> Option<&Path> {
1213        self.inner.get_current_dir()
1214    }
1215
1216    /// Returns whether the environment will be cleared for the child process.
1217    ///
1218    /// This returns `true` if [`Command::env_clear`] was called, and `false` otherwise.
1219    /// When `true`, the child process will not inherit any environment variables from
1220    /// its parent process.
1221    ///
1222    /// # Examples
1223    ///
1224    /// ```
1225    /// #![feature(command_resolved_envs)]
1226    /// use std::process::Command;
1227    ///
1228    /// let mut cmd = Command::new("ls");
1229    /// assert_eq!(cmd.get_env_clear(), false);
1230    ///
1231    /// cmd.env_clear();
1232    /// assert_eq!(cmd.get_env_clear(), true);
1233    /// ```
1234    #[must_use]
1235    #[unstable(feature = "command_resolved_envs", issue = "149070")]
1236    pub fn get_env_clear(&self) -> bool {
1237        self.inner.get_env_clear()
1238    }
1239}
1240
1241#[stable(feature = "rust1", since = "1.0.0")]
1242impl fmt::Debug for Command {
1243    /// Format the program and arguments of a Command for display. Any
1244    /// non-utf8 data is lossily converted using the utf8 replacement
1245    /// character.
1246    ///
1247    /// The default format approximates a shell invocation of the program along with its
1248    /// arguments. It does not include most of the other command properties. The output is not guaranteed to work
1249    /// (e.g. due to lack of shell-escaping or differences in path resolution).
1250    /// On some platforms you can use [the alternate syntax] to show more fields.
1251    ///
1252    /// Note that the debug implementation is platform-specific.
1253    ///
1254    /// [the alternate syntax]: fmt#sign0
1255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1256        self.inner.fmt(f)
1257    }
1258}
1259
1260impl AsInner<imp::Command> for Command {
1261    #[inline]
1262    fn as_inner(&self) -> &imp::Command {
1263        &self.inner
1264    }
1265}
1266
1267impl AsInnerMut<imp::Command> for Command {
1268    #[inline]
1269    fn as_inner_mut(&mut self) -> &mut imp::Command {
1270        &mut self.inner
1271    }
1272}
1273
1274/// An iterator over the command arguments.
1275///
1276/// This struct is created by [`Command::get_args`]. See its documentation for
1277/// more.
1278#[must_use = "iterators are lazy and do nothing unless consumed"]
1279#[stable(feature = "command_access", since = "1.57.0")]
1280#[derive(Debug)]
1281pub struct CommandArgs<'a> {
1282    inner: imp::CommandArgs<'a>,
1283}
1284
1285#[stable(feature = "command_access", since = "1.57.0")]
1286impl<'a> Iterator for CommandArgs<'a> {
1287    type Item = &'a OsStr;
1288    fn next(&mut self) -> Option<&'a OsStr> {
1289        self.inner.next()
1290    }
1291    fn size_hint(&self) -> (usize, Option<usize>) {
1292        self.inner.size_hint()
1293    }
1294}
1295
1296#[stable(feature = "command_access", since = "1.57.0")]
1297impl<'a> ExactSizeIterator for CommandArgs<'a> {
1298    fn len(&self) -> usize {
1299        self.inner.len()
1300    }
1301    fn is_empty(&self) -> bool {
1302        self.inner.is_empty()
1303    }
1304}
1305
1306/// An iterator over the command environment variables.
1307///
1308/// This struct is created by
1309/// [`Command::get_envs`][crate::process::Command::get_envs]. See its
1310/// documentation for more.
1311#[must_use = "iterators are lazy and do nothing unless consumed"]
1312#[stable(feature = "command_access", since = "1.57.0")]
1313pub struct CommandEnvs<'a> {
1314    iter: imp::CommandEnvs<'a>,
1315}
1316
1317#[stable(feature = "command_access", since = "1.57.0")]
1318impl<'a> Iterator for CommandEnvs<'a> {
1319    type Item = (&'a OsStr, Option<&'a OsStr>);
1320
1321    fn next(&mut self) -> Option<Self::Item> {
1322        self.iter.next()
1323    }
1324
1325    fn size_hint(&self) -> (usize, Option<usize>) {
1326        self.iter.size_hint()
1327    }
1328}
1329
1330#[stable(feature = "command_access", since = "1.57.0")]
1331impl<'a> ExactSizeIterator for CommandEnvs<'a> {
1332    fn len(&self) -> usize {
1333        self.iter.len()
1334    }
1335
1336    fn is_empty(&self) -> bool {
1337        self.iter.is_empty()
1338    }
1339}
1340
1341#[stable(feature = "command_access", since = "1.57.0")]
1342impl<'a> fmt::Debug for CommandEnvs<'a> {
1343    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1344        self.iter.fmt(f)
1345    }
1346}
1347
1348/// The output of a finished process.
1349///
1350/// This is returned in a Result by either the [`output`] method of a
1351/// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1352/// process.
1353///
1354/// [`output`]: Command::output
1355/// [`wait_with_output`]: Child::wait_with_output
1356#[derive(PartialEq, Eq, Clone)]
1357#[stable(feature = "process", since = "1.0.0")]
1358pub struct Output {
1359    /// The status (exit code) of the process.
1360    #[stable(feature = "process", since = "1.0.0")]
1361    pub status: ExitStatus,
1362    /// The data that the process wrote to stdout.
1363    #[stable(feature = "process", since = "1.0.0")]
1364    pub stdout: Vec<u8>,
1365    /// The data that the process wrote to stderr.
1366    #[stable(feature = "process", since = "1.0.0")]
1367    pub stderr: Vec<u8>,
1368}
1369
1370impl Output {
1371    /// Returns an error if a nonzero exit status was received.
1372    ///
1373    /// If the [`Command`] exited successfully,
1374    /// `self` is returned.
1375    ///
1376    /// This is equivalent to calling [`exit_ok`](ExitStatus::exit_ok)
1377    /// on [`Output.status`](Output::status).
1378    ///
1379    /// Note that this will throw away the [`Output::stderr`] field in the error case.
1380    /// If the child process outputs useful informantion to stderr, you can:
1381    /// * Use `cmd.stderr(Stdio::inherit())` to forward the
1382    ///   stderr child process to the parent's stderr,
1383    ///   usually printing it to console where the user can see it.
1384    ///   This is usually correct for command-line applications.
1385    /// * Capture `stderr` using a custom error type.
1386    ///   This is usually correct for libraries.
1387    ///
1388    /// # Examples
1389    ///
1390    /// ```
1391    /// #![feature(exit_status_error)]
1392    /// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
1393    /// # // required by `Command`.
1394    /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(target_os = "vxworks")))] {
1395    /// use std::process::Command;
1396    /// assert!(Command::new("false").output().unwrap().exit_ok().is_err());
1397    /// # }
1398    /// ```
1399    #[unstable(feature = "exit_status_error", issue = "84908")]
1400    pub fn exit_ok(self) -> Result<Self, ExitStatusError> {
1401        self.status.exit_ok()?;
1402        Ok(self)
1403    }
1404}
1405
1406// If either stderr or stdout are valid utf8 strings it prints the valid
1407// strings, otherwise it prints the byte sequence instead
1408#[stable(feature = "process_output_debug", since = "1.7.0")]
1409impl fmt::Debug for Output {
1410    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1411        let stdout_utf8 = str::from_utf8(&self.stdout);
1412        let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1413            Ok(ref s) => s,
1414            Err(_) => &self.stdout,
1415        };
1416
1417        let stderr_utf8 = str::from_utf8(&self.stderr);
1418        let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1419            Ok(ref s) => s,
1420            Err(_) => &self.stderr,
1421        };
1422
1423        fmt.debug_struct("Output")
1424            .field("status", &self.status)
1425            .field("stdout", stdout_debug)
1426            .field("stderr", stderr_debug)
1427            .finish()
1428    }
1429}
1430
1431/// Describes what to do with a standard I/O stream for a child process when
1432/// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1433///
1434/// [`stdin`]: Command::stdin
1435/// [`stdout`]: Command::stdout
1436/// [`stderr`]: Command::stderr
1437#[stable(feature = "process", since = "1.0.0")]
1438pub struct Stdio(imp::Stdio);
1439
1440impl Stdio {
1441    /// A new pipe should be arranged to connect the parent and child processes.
1442    ///
1443    /// # Examples
1444    ///
1445    /// With stdout:
1446    ///
1447    /// ```no_run
1448    /// use std::process::{Command, Stdio};
1449    ///
1450    /// let output = Command::new("echo")
1451    ///     .arg("Hello, world!")
1452    ///     .stdout(Stdio::piped())
1453    ///     .output()
1454    ///     .expect("Failed to execute command");
1455    ///
1456    /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1457    /// // Nothing echoed to console
1458    /// ```
1459    ///
1460    /// With stdin:
1461    ///
1462    /// ```no_run
1463    /// use std::io::Write;
1464    /// use std::process::{Command, Stdio};
1465    ///
1466    /// let mut child = Command::new("rev")
1467    ///     .stdin(Stdio::piped())
1468    ///     .stdout(Stdio::piped())
1469    ///     .spawn()
1470    ///     .expect("Failed to spawn child process");
1471    ///
1472    /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1473    /// std::thread::spawn(move || {
1474    ///     stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1475    /// });
1476    ///
1477    /// let output = child.wait_with_output().expect("Failed to read stdout");
1478    /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1479    /// ```
1480    ///
1481    /// Writing more than a pipe buffer's worth of input to stdin without also reading
1482    /// stdout and stderr at the same time may cause a deadlock.
1483    /// This is an issue when running any program that doesn't guarantee that it reads
1484    /// its entire stdin before writing more than a pipe buffer's worth of output.
1485    /// The size of a pipe buffer varies on different targets.
1486    ///
1487    #[must_use]
1488    #[stable(feature = "process", since = "1.0.0")]
1489    pub fn piped() -> Stdio {
1490        Stdio(imp::Stdio::MakePipe)
1491    }
1492
1493    /// The child inherits from the corresponding parent descriptor.
1494    ///
1495    /// # Examples
1496    ///
1497    /// With stdout:
1498    ///
1499    /// ```no_run
1500    /// use std::process::{Command, Stdio};
1501    ///
1502    /// let output = Command::new("echo")
1503    ///     .arg("Hello, world!")
1504    ///     .stdout(Stdio::inherit())
1505    ///     .output()
1506    ///     .expect("Failed to execute command");
1507    ///
1508    /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1509    /// // "Hello, world!" echoed to console
1510    /// ```
1511    ///
1512    /// With stdin:
1513    ///
1514    /// ```no_run
1515    /// use std::process::{Command, Stdio};
1516    /// use std::io::{self, Write};
1517    ///
1518    /// let output = Command::new("rev")
1519    ///     .stdin(Stdio::inherit())
1520    ///     .stdout(Stdio::piped())
1521    ///     .output()?;
1522    ///
1523    /// print!("You piped in the reverse of: ");
1524    /// io::stdout().write_all(&output.stdout)?;
1525    /// # io::Result::Ok(())
1526    /// ```
1527    #[must_use]
1528    #[stable(feature = "process", since = "1.0.0")]
1529    pub fn inherit() -> Stdio {
1530        Stdio(imp::Stdio::Inherit)
1531    }
1532
1533    /// This stream will be ignored. This is the equivalent of attaching the
1534    /// stream to `/dev/null`.
1535    ///
1536    /// # Examples
1537    ///
1538    /// With stdout:
1539    ///
1540    /// ```no_run
1541    /// use std::process::{Command, Stdio};
1542    ///
1543    /// let output = Command::new("echo")
1544    ///     .arg("Hello, world!")
1545    ///     .stdout(Stdio::null())
1546    ///     .output()
1547    ///     .expect("Failed to execute command");
1548    ///
1549    /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1550    /// // Nothing echoed to console
1551    /// ```
1552    ///
1553    /// With stdin:
1554    ///
1555    /// ```no_run
1556    /// use std::process::{Command, Stdio};
1557    ///
1558    /// let output = Command::new("rev")
1559    ///     .stdin(Stdio::null())
1560    ///     .stdout(Stdio::piped())
1561    ///     .output()
1562    ///     .expect("Failed to execute command");
1563    ///
1564    /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1565    /// // Ignores any piped-in input
1566    /// ```
1567    #[must_use]
1568    #[stable(feature = "process", since = "1.0.0")]
1569    pub fn null() -> Stdio {
1570        Stdio(imp::Stdio::Null)
1571    }
1572
1573    /// Returns `true` if this requires [`Command`] to create a new pipe.
1574    ///
1575    /// # Example
1576    ///
1577    /// ```
1578    /// #![feature(stdio_makes_pipe)]
1579    /// use std::process::Stdio;
1580    ///
1581    /// let io = Stdio::piped();
1582    /// assert_eq!(io.makes_pipe(), true);
1583    /// ```
1584    #[unstable(feature = "stdio_makes_pipe", issue = "98288")]
1585    pub fn makes_pipe(&self) -> bool {
1586        matches!(self.0, imp::Stdio::MakePipe)
1587    }
1588}
1589
1590impl FromInner<imp::Stdio> for Stdio {
1591    fn from_inner(inner: imp::Stdio) -> Stdio {
1592        Stdio(inner)
1593    }
1594}
1595
1596#[stable(feature = "std_debug", since = "1.16.0")]
1597impl fmt::Debug for Stdio {
1598    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1599        f.debug_struct("Stdio").finish_non_exhaustive()
1600    }
1601}
1602
1603#[stable(feature = "stdio_from", since = "1.20.0")]
1604impl From<ChildStdin> for Stdio {
1605    /// Converts a [`ChildStdin`] into a [`Stdio`].
1606    ///
1607    /// # Examples
1608    ///
1609    /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1610    ///
1611    /// ```rust,no_run
1612    /// use std::process::{Command, Stdio};
1613    ///
1614    /// let reverse = Command::new("rev")
1615    ///     .stdin(Stdio::piped())
1616    ///     .spawn()
1617    ///     .expect("failed reverse command");
1618    ///
1619    /// let _echo = Command::new("echo")
1620    ///     .arg("Hello, world!")
1621    ///     .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1622    ///     .output()
1623    ///     .expect("failed echo command");
1624    ///
1625    /// // "!dlrow ,olleH" echoed to console
1626    /// ```
1627    fn from(child: ChildStdin) -> Stdio {
1628        Stdio::from_inner(child.into_inner().into())
1629    }
1630}
1631
1632#[stable(feature = "stdio_from", since = "1.20.0")]
1633impl From<ChildStdout> for Stdio {
1634    /// Converts a [`ChildStdout`] into a [`Stdio`].
1635    ///
1636    /// # Examples
1637    ///
1638    /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1639    ///
1640    /// ```rust,no_run
1641    /// use std::process::{Command, Stdio};
1642    ///
1643    /// let hello = Command::new("echo")
1644    ///     .arg("Hello, world!")
1645    ///     .stdout(Stdio::piped())
1646    ///     .spawn()
1647    ///     .expect("failed echo command");
1648    ///
1649    /// let reverse = Command::new("rev")
1650    ///     .stdin(hello.stdout.unwrap())  // Converted into a Stdio here
1651    ///     .output()
1652    ///     .expect("failed reverse command");
1653    ///
1654    /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1655    /// ```
1656    fn from(child: ChildStdout) -> Stdio {
1657        Stdio::from_inner(child.into_inner().into())
1658    }
1659}
1660
1661#[stable(feature = "stdio_from", since = "1.20.0")]
1662impl From<ChildStderr> for Stdio {
1663    /// Converts a [`ChildStderr`] into a [`Stdio`].
1664    ///
1665    /// # Examples
1666    ///
1667    /// ```rust,no_run
1668    /// use std::process::{Command, Stdio};
1669    ///
1670    /// let reverse = Command::new("rev")
1671    ///     .arg("non_existing_file.txt")
1672    ///     .stderr(Stdio::piped())
1673    ///     .spawn()
1674    ///     .expect("failed reverse command");
1675    ///
1676    /// let cat = Command::new("cat")
1677    ///     .arg("-")
1678    ///     .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1679    ///     .output()
1680    ///     .expect("failed echo command");
1681    ///
1682    /// assert_eq!(
1683    ///     String::from_utf8_lossy(&cat.stdout),
1684    ///     "rev: cannot open non_existing_file.txt: No such file or directory\n"
1685    /// );
1686    /// ```
1687    fn from(child: ChildStderr) -> Stdio {
1688        Stdio::from_inner(child.into_inner().into())
1689    }
1690}
1691
1692#[stable(feature = "stdio_from", since = "1.20.0")]
1693impl From<fs::File> for Stdio {
1694    /// Converts a [`File`](fs::File) into a [`Stdio`].
1695    ///
1696    /// # Examples
1697    ///
1698    /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1699    ///
1700    /// ```rust,no_run
1701    /// use std::fs::File;
1702    /// use std::process::Command;
1703    ///
1704    /// // With the `foo.txt` file containing "Hello, world!"
1705    /// let file = File::open("foo.txt")?;
1706    ///
1707    /// let reverse = Command::new("rev")
1708    ///     .stdin(file)  // Implicit File conversion into a Stdio
1709    ///     .output()?;
1710    ///
1711    /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1712    /// # std::io::Result::Ok(())
1713    /// ```
1714    fn from(file: fs::File) -> Stdio {
1715        Stdio::from_inner(file.into_inner().into())
1716    }
1717}
1718
1719#[stable(feature = "stdio_from_stdio", since = "1.74.0")]
1720impl From<io::Stdout> for Stdio {
1721    /// Redirect command stdout/stderr to our stdout
1722    ///
1723    /// # Examples
1724    ///
1725    /// ```rust
1726    /// #![feature(exit_status_error)]
1727    /// use std::io;
1728    /// use std::process::Command;
1729    ///
1730    /// # fn test() -> Result<(), Box<dyn std::error::Error>> {
1731    /// let output = Command::new("whoami")
1732    // "whoami" is a command which exists on both Unix and Windows,
1733    // and which succeeds, producing some stdout output but no stderr.
1734    ///     .stdout(io::stdout())
1735    ///     .output()?;
1736    /// output.status.exit_ok()?;
1737    /// assert!(output.stdout.is_empty());
1738    /// # Ok(())
1739    /// # }
1740    /// #
1741    /// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
1742    /// # // required by `Command`.
1743    /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(target_os = "vxworks"))) {
1744    /// #     test().unwrap();
1745    /// # }
1746    /// ```
1747    fn from(inherit: io::Stdout) -> Stdio {
1748        Stdio::from_inner(inherit.into())
1749    }
1750}
1751
1752#[stable(feature = "stdio_from_stdio", since = "1.74.0")]
1753impl From<io::Stderr> for Stdio {
1754    /// Redirect command stdout/stderr to our stderr
1755    ///
1756    /// # Examples
1757    ///
1758    /// ```rust
1759    /// #![feature(exit_status_error)]
1760    /// use std::io;
1761    /// use std::process::Command;
1762    ///
1763    /// # fn test() -> Result<(), Box<dyn std::error::Error>> {
1764    /// let output = Command::new("whoami")
1765    ///     .stdout(io::stderr())
1766    ///     .output()?;
1767    /// output.status.exit_ok()?;
1768    /// assert!(output.stdout.is_empty());
1769    /// # Ok(())
1770    /// # }
1771    /// #
1772    /// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
1773    /// # // required by `Command`.
1774    /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(target_os = "vxworks"))) {
1775    /// #     test().unwrap();
1776    /// # }
1777    /// ```
1778    fn from(inherit: io::Stderr) -> Stdio {
1779        Stdio::from_inner(inherit.into())
1780    }
1781}
1782
1783#[stable(feature = "anonymous_pipe", since = "1.87.0")]
1784impl From<io::PipeWriter> for Stdio {
1785    fn from(pipe: io::PipeWriter) -> Self {
1786        Stdio::from_inner(pipe.into_inner().into())
1787    }
1788}
1789
1790#[stable(feature = "anonymous_pipe", since = "1.87.0")]
1791impl From<io::PipeReader> for Stdio {
1792    fn from(pipe: io::PipeReader) -> Self {
1793        Stdio::from_inner(pipe.into_inner().into())
1794    }
1795}
1796
1797/// Describes the result of a process after it has terminated.
1798///
1799/// This `struct` is used to represent the exit status or other termination of a child process.
1800/// Child processes are created via the [`Command`] struct and their exit
1801/// status is exposed through the [`status`] method, or the [`wait`] method
1802/// of a [`Child`] process.
1803///
1804/// An `ExitStatus` represents every possible disposition of a process.  On Unix this
1805/// is the **wait status**.  It is *not* simply an *exit status* (a value passed to `exit`).
1806///
1807/// For proper error reporting of failed processes, print the value of `ExitStatus` or
1808/// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1809///
1810/// # Differences from `ExitCode`
1811///
1812/// [`ExitCode`] is intended for terminating the currently running process, via
1813/// the `Termination` trait, in contrast to `ExitStatus`, which represents the
1814/// termination of a child process. These APIs are separate due to platform
1815/// compatibility differences and their expected usage; it is not generally
1816/// possible to exactly reproduce an `ExitStatus` from a child for the current
1817/// process after the fact.
1818///
1819/// [`status`]: Command::status
1820/// [`wait`]: Child::wait
1821//
1822// We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1823// vs `_exit`.  Naming of Unix system calls is not standardised across Unices, so terminology is a
1824// matter of convention and tradition.  For clarity we usually speak of `exit`, even when we might
1825// mean an underlying system call such as `_exit`.
1826#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1827#[stable(feature = "process", since = "1.0.0")]
1828pub struct ExitStatus(imp::ExitStatus);
1829
1830/// The default value is one which indicates successful completion.
1831#[stable(feature = "process_exitstatus_default", since = "1.73.0")]
1832impl Default for ExitStatus {
1833    fn default() -> Self {
1834        // Ideally this would be done by ExitCode::default().into() but that is complicated.
1835        ExitStatus::from_inner(imp::ExitStatus::default())
1836    }
1837}
1838
1839/// Allows extension traits within `std`.
1840#[unstable(feature = "sealed", issue = "none")]
1841impl crate::sealed::Sealed for ExitStatus {}
1842
1843impl ExitStatus {
1844    /// Was termination successful?  Returns a `Result`.
1845    ///
1846    /// # Examples
1847    ///
1848    /// ```
1849    /// #![feature(exit_status_error)]
1850    /// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
1851    /// # // required by `Command`.
1852    /// # if cfg!(all(unix, not(all(target_vendor = "apple", not(target_os = "macos"))), not(target_os = "vxworks"))) {
1853    /// use std::process::Command;
1854    ///
1855    /// let status = Command::new("ls")
1856    ///     .arg("/dev/nonexistent")
1857    ///     .status()
1858    ///     .expect("ls could not be executed");
1859    ///
1860    /// println!("ls: {status}");
1861    /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1862    /// # } // cfg!(unix)
1863    /// ```
1864    #[unstable(feature = "exit_status_error", issue = "84908")]
1865    pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1866        self.0.exit_ok().map_err(ExitStatusError)
1867    }
1868
1869    /// Was termination successful? Signal termination is not considered a
1870    /// success, and success is defined as a zero exit status.
1871    ///
1872    /// # Examples
1873    ///
1874    /// ```rust,no_run
1875    /// use std::process::Command;
1876    ///
1877    /// let status = Command::new("mkdir")
1878    ///     .arg("projects")
1879    ///     .status()
1880    ///     .expect("failed to execute mkdir");
1881    ///
1882    /// if status.success() {
1883    ///     println!("'projects/' directory created");
1884    /// } else {
1885    ///     println!("failed to create 'projects/' directory: {status}");
1886    /// }
1887    /// ```
1888    #[must_use]
1889    #[stable(feature = "process", since = "1.0.0")]
1890    pub fn success(&self) -> bool {
1891        self.0.exit_ok().is_ok()
1892    }
1893
1894    /// Returns the exit code of the process, if any.
1895    ///
1896    /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1897    /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1898    /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1899    /// runtime system (often, for example, 255, 254, 127 or 126).
1900    ///
1901    /// On Unix, this will return `None` if the process was terminated by a signal.
1902    /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1903    /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1904    ///
1905    /// # Examples
1906    ///
1907    /// ```no_run
1908    /// use std::process::Command;
1909    ///
1910    /// let status = Command::new("mkdir")
1911    ///     .arg("projects")
1912    ///     .status()
1913    ///     .expect("failed to execute mkdir");
1914    ///
1915    /// match status.code() {
1916    ///     Some(code) => println!("Exited with status code: {code}"),
1917    ///     None => println!("Process terminated by signal")
1918    /// }
1919    /// ```
1920    #[must_use]
1921    #[stable(feature = "process", since = "1.0.0")]
1922    pub fn code(&self) -> Option<i32> {
1923        self.0.code()
1924    }
1925}
1926
1927impl AsInner<imp::ExitStatus> for ExitStatus {
1928    #[inline]
1929    fn as_inner(&self) -> &imp::ExitStatus {
1930        &self.0
1931    }
1932}
1933
1934impl FromInner<imp::ExitStatus> for ExitStatus {
1935    fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1936        ExitStatus(s)
1937    }
1938}
1939
1940#[stable(feature = "process", since = "1.0.0")]
1941impl fmt::Display for ExitStatus {
1942    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1943        self.0.fmt(f)
1944    }
1945}
1946
1947/// Allows extension traits within `std`.
1948#[unstable(feature = "sealed", issue = "none")]
1949impl crate::sealed::Sealed for ExitStatusError {}
1950
1951/// Describes the result of a process after it has failed
1952///
1953/// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1954///
1955/// # Examples
1956///
1957/// ```
1958/// #![feature(exit_status_error)]
1959/// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
1960/// # // required by `Command`.
1961/// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(target_os = "vxworks"))) {
1962/// use std::process::{Command, ExitStatusError};
1963///
1964/// fn run(cmd: &str) -> Result<(), ExitStatusError> {
1965///     Command::new(cmd).status().unwrap().exit_ok()?;
1966///     Ok(())
1967/// }
1968///
1969/// run("true").unwrap();
1970/// run("false").unwrap_err();
1971/// # } // cfg!(unix)
1972/// ```
1973#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1974#[unstable(feature = "exit_status_error", issue = "84908")]
1975// The definition of imp::ExitStatusError should ideally be such that
1976// Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1977pub struct ExitStatusError(imp::ExitStatusError);
1978
1979#[unstable(feature = "exit_status_error", issue = "84908")]
1980impl ExitStatusError {
1981    /// Reports the exit code, if applicable, from an `ExitStatusError`.
1982    ///
1983    /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1984    /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1985    /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1986    /// runtime system (often, for example, 255, 254, 127 or 126).
1987    ///
1988    /// On Unix, this will return `None` if the process was terminated by a signal.  If you want to
1989    /// handle such situations specially, consider using methods from
1990    /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1991    ///
1992    /// If the process finished by calling `exit` with a nonzero value, this will return
1993    /// that exit status.
1994    ///
1995    /// If the error was something else, it will return `None`.
1996    ///
1997    /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1998    /// `ExitStatusError`.  So the return value from `ExitStatusError::code()` is always nonzero.
1999    ///
2000    /// # Examples
2001    ///
2002    /// ```
2003    /// #![feature(exit_status_error)]
2004    /// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
2005    /// # // required by `Command`.
2006    /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(target_os = "vxworks")))] {
2007    /// use std::process::Command;
2008    ///
2009    /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
2010    /// assert_eq!(bad.code(), Some(1));
2011    /// # } // #[cfg(unix)]
2012    /// ```
2013    #[must_use]
2014    pub fn code(&self) -> Option<i32> {
2015        self.code_nonzero().map(Into::into)
2016    }
2017
2018    /// Reports the exit code, if applicable, from an `ExitStatusError`, as a [`NonZero`].
2019    ///
2020    /// This is exactly like [`code()`](Self::code), except that it returns a <code>[NonZero]<[i32]></code>.
2021    ///
2022    /// Plain `code`, returning a plain integer, is provided because it is often more convenient.
2023    /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
2024    /// a type-level guarantee of nonzeroness.
2025    ///
2026    /// # Examples
2027    ///
2028    /// ```
2029    /// #![feature(exit_status_error)]
2030    ///
2031    /// # // AdaCore: On VxWorks the shell and utilities are kernel built-ins, not executables
2032    /// # // required by `Command`.
2033    /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(target_os = "vxworks"))) {
2034    /// use std::num::NonZero;
2035    /// use std::process::Command;
2036    ///
2037    /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
2038    /// assert_eq!(bad.code_nonzero().unwrap(), NonZero::new(1).unwrap());
2039    /// # } // cfg!(unix)
2040    /// ```
2041    #[must_use]
2042    pub fn code_nonzero(&self) -> Option<NonZero<i32>> {
2043        self.0.code()
2044    }
2045
2046    /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
2047    #[must_use]
2048    pub fn into_status(&self) -> ExitStatus {
2049        ExitStatus(self.0.into())
2050    }
2051}
2052
2053#[unstable(feature = "exit_status_error", issue = "84908")]
2054impl From<ExitStatusError> for ExitStatus {
2055    fn from(error: ExitStatusError) -> Self {
2056        Self(error.0.into())
2057    }
2058}
2059
2060#[unstable(feature = "exit_status_error", issue = "84908")]
2061impl fmt::Display for ExitStatusError {
2062    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2063        write!(f, "process exited unsuccessfully: {}", self.into_status())
2064    }
2065}
2066
2067#[unstable(feature = "exit_status_error", issue = "84908")]
2068impl crate::error::Error for ExitStatusError {}
2069
2070/// This type represents the status code the current process can return
2071/// to its parent under normal termination.
2072///
2073/// `ExitCode` is intended to be consumed only by the standard library (via
2074/// [`Termination::report()`]). For forwards compatibility with potentially
2075/// unusual targets, this type currently does not provide `Eq`, `Hash`, or
2076/// access to the raw value. This type does provide `PartialEq` for
2077/// comparison, but note that there may potentially be multiple failure
2078/// codes, some of which will _not_ compare equal to `ExitCode::FAILURE`.
2079/// The standard library provides the canonical `SUCCESS` and `FAILURE`
2080/// exit codes as well as `From<u8> for ExitCode` for constructing other
2081/// arbitrary exit codes.
2082///
2083/// # Portability
2084///
2085/// Numeric values used in this type don't have portable meanings, and
2086/// different platforms may mask different amounts of them.
2087///
2088/// For the platform's canonical successful and unsuccessful codes, see
2089/// the [`SUCCESS`] and [`FAILURE`] associated items.
2090///
2091/// [`SUCCESS`]: ExitCode::SUCCESS
2092/// [`FAILURE`]: ExitCode::FAILURE
2093///
2094/// # Differences from `ExitStatus`
2095///
2096/// `ExitCode` is intended for terminating the currently running process, via
2097/// the `Termination` trait, in contrast to [`ExitStatus`], which represents the
2098/// termination of a child process. These APIs are separate due to platform
2099/// compatibility differences and their expected usage; it is not generally
2100/// possible to exactly reproduce an `ExitStatus` from a child for the current
2101/// process after the fact.
2102///
2103/// # Examples
2104///
2105/// `ExitCode` can be returned from the `main` function of a crate, as it implements
2106/// [`Termination`]:
2107///
2108/// ```
2109/// use std::process::ExitCode;
2110/// # fn check_foo() -> bool { true }
2111///
2112/// fn main() -> ExitCode {
2113///     if !check_foo() {
2114///         return ExitCode::from(42);
2115///     }
2116///
2117///     ExitCode::SUCCESS
2118/// }
2119/// ```
2120#[derive(Clone, Copy, Debug, PartialEq)]
2121#[stable(feature = "process_exitcode", since = "1.61.0")]
2122pub struct ExitCode(imp::ExitCode);
2123
2124/// Allows extension traits within `std`.
2125#[unstable(feature = "sealed", issue = "none")]
2126impl crate::sealed::Sealed for ExitCode {}
2127
2128#[stable(feature = "process_exitcode", since = "1.61.0")]
2129impl ExitCode {
2130    /// The canonical `ExitCode` for successful termination on this platform.
2131    ///
2132    /// Note that a `()`-returning `main` implicitly results in a successful
2133    /// termination, so there's no need to return this from `main` unless
2134    /// you're also returning other possible codes.
2135    #[stable(feature = "process_exitcode", since = "1.61.0")]
2136    pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
2137
2138    /// The canonical `ExitCode` for unsuccessful termination on this platform.
2139    ///
2140    /// If you're only returning this and `SUCCESS` from `main`, consider
2141    /// instead returning `Err(_)` and `Ok(())` respectively, which will
2142    /// return the same codes (but will also `eprintln!` the error).
2143    #[stable(feature = "process_exitcode", since = "1.61.0")]
2144    pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
2145
2146    /// Exit the current process with the given `ExitCode`.
2147    ///
2148    /// Note that this has the same caveats as [`process::exit()`][exit], namely that this function
2149    /// terminates the process immediately, so no destructors on the current stack or any other
2150    /// thread's stack will be run. Also see those docs for some important notes on interop with C
2151    /// code. If a clean shutdown is needed, it is recommended to simply return this ExitCode from
2152    /// the `main` function, as demonstrated in the [type documentation](#examples).
2153    ///
2154    /// # Differences from `process::exit()`
2155    ///
2156    /// `process::exit()` accepts any `i32` value as the exit code for the process; however, there
2157    /// are platforms that only use a subset of that value (see [`process::exit` platform-specific
2158    /// behavior][exit#platform-specific-behavior]). `ExitCode` exists because of this; only
2159    /// `ExitCode`s that are supported by a majority of our platforms can be created, so those
2160    /// problems don't exist (as much) with this method.
2161    ///
2162    /// # Examples
2163    ///
2164    /// ```
2165    /// #![feature(exitcode_exit_method)]
2166    /// # use std::process::ExitCode;
2167    /// # use std::fmt;
2168    /// # enum UhOhError { GenericProblem, Specific, WithCode { exit_code: ExitCode, _x: () } }
2169    /// # impl fmt::Display for UhOhError {
2170    /// #     fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { unimplemented!() }
2171    /// # }
2172    /// // there's no way to gracefully recover from an UhOhError, so we just
2173    /// // print a message and exit
2174    /// fn handle_unrecoverable_error(err: UhOhError) -> ! {
2175    ///     eprintln!("UH OH! {err}");
2176    ///     let code = match err {
2177    ///         UhOhError::GenericProblem => ExitCode::FAILURE,
2178    ///         UhOhError::Specific => ExitCode::from(3),
2179    ///         UhOhError::WithCode { exit_code, .. } => exit_code,
2180    ///     };
2181    ///     code.exit_process()
2182    /// }
2183    /// ```
2184    #[unstable(feature = "exitcode_exit_method", issue = "97100")]
2185    pub fn exit_process(self) -> ! {
2186        exit(self.to_i32())
2187    }
2188}
2189
2190impl ExitCode {
2191    // This is private/perma-unstable because ExitCode is opaque; we don't know that i32 will serve
2192    // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
2193    // likely want to isolate users anything that could restrict the platform specific
2194    // representation of an ExitCode
2195    //
2196    // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
2197    /// Converts an `ExitCode` into an i32
2198    #[unstable(
2199        feature = "process_exitcode_internals",
2200        reason = "exposed only for libstd",
2201        issue = "none"
2202    )]
2203    #[inline]
2204    #[doc(hidden)]
2205    pub fn to_i32(self) -> i32 {
2206        self.0.as_i32()
2207    }
2208}
2209
2210/// The default value is [`ExitCode::SUCCESS`]
2211#[stable(feature = "process_exitcode_default", since = "1.75.0")]
2212impl Default for ExitCode {
2213    fn default() -> Self {
2214        ExitCode::SUCCESS
2215    }
2216}
2217
2218#[stable(feature = "process_exitcode", since = "1.61.0")]
2219impl From<u8> for ExitCode {
2220    /// Constructs an `ExitCode` from an arbitrary u8 value.
2221    fn from(code: u8) -> Self {
2222        ExitCode(imp::ExitCode::from(code))
2223    }
2224}
2225
2226impl AsInner<imp::ExitCode> for ExitCode {
2227    #[inline]
2228    fn as_inner(&self) -> &imp::ExitCode {
2229        &self.0
2230    }
2231}
2232
2233impl FromInner<imp::ExitCode> for ExitCode {
2234    fn from_inner(s: imp::ExitCode) -> ExitCode {
2235        ExitCode(s)
2236    }
2237}
2238
2239impl Child {
2240    /// Forces the child process to exit. If the child has already exited, `Ok(())`
2241    /// is returned.
2242    ///
2243    /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
2244    ///
2245    /// This is equivalent to sending a SIGKILL on Unix platforms.
2246    ///
2247    /// # Examples
2248    ///
2249    /// ```no_run
2250    /// use std::process::Command;
2251    ///
2252    /// let mut command = Command::new("yes");
2253    /// if let Ok(mut child) = command.spawn() {
2254    ///     child.kill().expect("command couldn't be killed");
2255    /// } else {
2256    ///     println!("yes command didn't start");
2257    /// }
2258    /// ```
2259    ///
2260    /// [`ErrorKind`]: io::ErrorKind
2261    /// [`InvalidInput`]: io::ErrorKind::InvalidInput
2262    #[stable(feature = "process", since = "1.0.0")]
2263    #[cfg_attr(not(test), rustc_diagnostic_item = "child_kill")]
2264    pub fn kill(&mut self) -> io::Result<()> {
2265        self.handle.kill()
2266    }
2267
2268    /// Returns the OS-assigned process identifier associated with this child.
2269    ///
2270    /// # Examples
2271    ///
2272    /// ```no_run
2273    /// use std::process::Command;
2274    ///
2275    /// let mut command = Command::new("ls");
2276    /// if let Ok(child) = command.spawn() {
2277    ///     println!("Child's ID is {}", child.id());
2278    /// } else {
2279    ///     println!("ls command didn't start");
2280    /// }
2281    /// ```
2282    #[must_use]
2283    #[stable(feature = "process_id", since = "1.3.0")]
2284    #[cfg_attr(not(test), rustc_diagnostic_item = "child_id")]
2285    pub fn id(&self) -> u32 {
2286        self.handle.id()
2287    }
2288
2289    /// Waits for the child to exit completely, returning the status that it
2290    /// exited with. This function will continue to have the same return value
2291    /// after it has been called at least once.
2292    ///
2293    /// The stdin handle to the child process, if any, will be closed
2294    /// before waiting. This helps avoid deadlock: it ensures that the
2295    /// child does not block waiting for input from the parent, while
2296    /// the parent waits for the child to exit.
2297    ///
2298    /// # Examples
2299    ///
2300    /// ```no_run
2301    /// use std::process::Command;
2302    ///
2303    /// let mut command = Command::new("ls");
2304    /// if let Ok(mut child) = command.spawn() {
2305    ///     child.wait().expect("command wasn't running");
2306    ///     println!("Child has finished its execution!");
2307    /// } else {
2308    ///     println!("ls command didn't start");
2309    /// }
2310    /// ```
2311    #[stable(feature = "process", since = "1.0.0")]
2312    pub fn wait(&mut self) -> io::Result<ExitStatus> {
2313        drop(self.stdin.take());
2314        self.handle.wait().map(ExitStatus)
2315    }
2316
2317    /// Attempts to collect the exit status of the child if it has already
2318    /// exited.
2319    ///
2320    /// This function will not block the calling thread and will only
2321    /// check to see if the child process has exited or not. If the child has
2322    /// exited then on Unix the process ID is reaped. This function is
2323    /// guaranteed to repeatedly return a successful exit status so long as the
2324    /// child has already exited.
2325    ///
2326    /// If the child has exited, then `Ok(Some(status))` is returned. If the
2327    /// exit status is not available at this time then `Ok(None)` is returned.
2328    /// If an error occurs, then that error is returned.
2329    ///
2330    /// Note that unlike `wait`, this function will not attempt to drop stdin.
2331    ///
2332    /// # Examples
2333    ///
2334    /// ```no_run
2335    /// use std::process::Command;
2336    ///
2337    /// let mut child = Command::new("ls").spawn()?;
2338    ///
2339    /// match child.try_wait() {
2340    ///     Ok(Some(status)) => println!("exited with: {status}"),
2341    ///     Ok(None) => {
2342    ///         println!("status not ready yet, let's really wait");
2343    ///         let res = child.wait();
2344    ///         println!("result: {res:?}");
2345    ///     }
2346    ///     Err(e) => println!("error attempting to wait: {e}"),
2347    /// }
2348    /// # std::io::Result::Ok(())
2349    /// ```
2350    #[stable(feature = "process_try_wait", since = "1.18.0")]
2351    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
2352        Ok(self.handle.try_wait()?.map(ExitStatus))
2353    }
2354
2355    /// Simultaneously waits for the child to exit and collect all remaining
2356    /// output on the stdout/stderr handles, returning an `Output`
2357    /// instance.
2358    ///
2359    /// The stdin handle to the child process, if any, will be closed
2360    /// before waiting. This helps avoid deadlock: it ensures that the
2361    /// child does not block waiting for input from the parent, while
2362    /// the parent waits for the child to exit.
2363    ///
2364    /// By default, stdin, stdout and stderr are inherited from the parent.
2365    /// In order to capture the output into this `Result<Output>` it is
2366    /// necessary to create new pipes between parent and child. Use
2367    /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
2368    ///
2369    /// # Examples
2370    ///
2371    /// ```should_panic
2372    /// use std::process::{Command, Stdio};
2373    ///
2374    /// let child = Command::new("/bin/cat")
2375    ///     .arg("file.txt")
2376    ///     .stdout(Stdio::piped())
2377    ///     .spawn()
2378    ///     .expect("failed to execute child");
2379    ///
2380    /// let output = child
2381    ///     .wait_with_output()
2382    ///     .expect("failed to wait on child");
2383    ///
2384    /// assert!(output.status.success());
2385    /// ```
2386    ///
2387    #[stable(feature = "process", since = "1.0.0")]
2388    pub fn wait_with_output(mut self) -> io::Result<Output> {
2389        drop(self.stdin.take());
2390
2391        let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
2392        match (self.stdout.take(), self.stderr.take()) {
2393            (None, None) => {}
2394            (Some(mut out), None) => {
2395                let res = out.read_to_end(&mut stdout);
2396                res.unwrap();
2397            }
2398            (None, Some(mut err)) => {
2399                let res = err.read_to_end(&mut stderr);
2400                res.unwrap();
2401            }
2402            (Some(out), Some(err)) => {
2403                let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
2404                res.unwrap();
2405            }
2406        }
2407
2408        let status = self.wait()?;
2409        Ok(Output { status, stdout, stderr })
2410    }
2411}
2412
2413/// Terminates the current process with the specified exit code.
2414///
2415/// This function will never return and will immediately terminate the current
2416/// process. The exit code is passed through to the underlying OS and will be
2417/// available for consumption by another process.
2418///
2419/// Note that because this function never returns, and that it terminates the
2420/// process, no destructors on the current stack or any other thread's stack
2421/// will be run. If a clean shutdown is needed it is recommended to only call
2422/// this function at a known point where there are no more destructors left
2423/// to run; or, preferably, simply return a type implementing [`Termination`]
2424/// (such as [`ExitCode`] or `Result`) from the `main` function and avoid this
2425/// function altogether:
2426///
2427/// ```
2428/// # use std::io::Error as MyError;
2429/// fn main() -> Result<(), MyError> {
2430///     // ...
2431///     Ok(())
2432/// }
2433/// ```
2434///
2435/// In its current implementation, this function will execute exit handlers registered with `atexit`
2436/// as well as other platform-specific exit handlers (e.g. `fini` sections of ELF shared objects).
2437/// This means that Rust requires that all exit handlers are safe to execute at any time. In
2438/// particular, if an exit handler cleans up some state that might be concurrently accessed by other
2439/// threads, it is required that the exit handler performs suitable synchronization with those
2440/// threads. (The alternative to this requirement would be to not run exit handlers at all, which is
2441/// considered undesirable. Note that returning from `main` also calls `exit`, so making `exit` an
2442/// unsafe operation is not an option.)
2443///
2444/// ## Platform-specific behavior
2445///
2446/// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
2447/// will be visible to a parent process inspecting the exit code. On most
2448/// Unix-like platforms, only the eight least-significant bits are considered.
2449///
2450/// For example, the exit code for this example will be `0` on Linux, but `256`
2451/// on Windows:
2452///
2453/// ```no_run
2454/// use std::process;
2455///
2456/// process::exit(0x0100);
2457/// ```
2458///
2459/// ### Safe interop with C code
2460///
2461/// On Unix, this function is currently implemented using the `exit` C function [`exit`][C-exit]. As
2462/// of C23, the C standard does not permit multiple threads to call `exit` concurrently. Rust
2463/// mitigates this with a lock, but if C code calls `exit`, that can still cause undefined behavior.
2464/// Note that returning from `main` is equivalent to calling `exit`.
2465///
2466/// Therefore, it is undefined behavior to have two concurrent threads perform the following
2467/// without synchronization:
2468/// - One thread calls Rust's `exit` function or returns from Rust's `main` function
2469/// - Another thread calls the C function `exit` or `quick_exit`, or returns from C's `main` function
2470///
2471/// Note that if a binary contains multiple copies of the Rust runtime (e.g., when combining
2472/// multiple `cdylib` or `staticlib`), they each have their own separate lock, so from the
2473/// perspective of code running in one of the Rust runtimes, the "outside" Rust code is basically C
2474/// code, and concurrent `exit` again causes undefined behavior.
2475///
2476/// Individual C implementations might provide more guarantees than the standard and permit concurrent
2477/// calls to `exit`; consult the documentation of your C implementation for details.
2478///
2479/// For some of the on-going discussion to make `exit` thread-safe in C, see:
2480/// - [Rust issue #126600](https://github.com/rust-lang/rust/issues/126600)
2481/// - [Austin Group Bugzilla (for POSIX)](https://austingroupbugs.net/view.php?id=1845)
2482/// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=31997)
2483///
2484/// [C-exit]: https://en.cppreference.com/w/c/program/exit
2485#[stable(feature = "rust1", since = "1.0.0")]
2486#[cfg_attr(not(test), rustc_diagnostic_item = "process_exit")]
2487pub fn exit(code: i32) -> ! {
2488    crate::rt::cleanup();
2489    crate::sys::os::exit(code)
2490}
2491
2492/// Terminates the process in an abnormal fashion.
2493///
2494/// The function will never return and will immediately terminate the current
2495/// process in a platform specific "abnormal" manner. As a consequence,
2496/// no destructors on the current stack or any other thread's stack
2497/// will be run, Rust IO buffers (eg, from `BufWriter`) will not be flushed,
2498/// and C stdio buffers will (on most platforms) not be flushed.
2499///
2500/// This is in contrast to the default behavior of [`panic!`] which unwinds
2501/// the current thread's stack and calls all destructors.
2502/// When `panic="abort"` is set, either as an argument to `rustc` or in a
2503/// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
2504/// [`panic!`] will still call the [panic hook] while `abort` will not.
2505///
2506/// If a clean shutdown is needed it is recommended to only call
2507/// this function at a known point where there are no more destructors left
2508/// to run.
2509///
2510/// The process's termination will be similar to that from the C `abort()`
2511/// function.  On Unix, the process will terminate with signal `SIGABRT`, which
2512/// typically means that the shell prints "Aborted".
2513///
2514/// # Examples
2515///
2516/// ```no_run
2517/// use std::process;
2518///
2519/// fn main() {
2520///     println!("aborting");
2521///
2522///     process::abort();
2523///
2524///     // execution never gets here
2525/// }
2526/// ```
2527///
2528/// The `abort` function terminates the process, so the destructor will not
2529/// get run on the example below:
2530///
2531/// ```no_run
2532/// use std::process;
2533///
2534/// struct HasDrop;
2535///
2536/// impl Drop for HasDrop {
2537///     fn drop(&mut self) {
2538///         println!("This will never be printed!");
2539///     }
2540/// }
2541///
2542/// fn main() {
2543///     let _x = HasDrop;
2544///     process::abort();
2545///     // the destructor implemented for HasDrop will never get run
2546/// }
2547/// ```
2548///
2549/// [panic hook]: crate::panic::set_hook
2550#[stable(feature = "process_abort", since = "1.17.0")]
2551#[cold]
2552#[cfg_attr(not(test), rustc_diagnostic_item = "process_abort")]
2553#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2554pub fn abort() -> ! {
2555    crate::sys::abort_internal();
2556}
2557
2558/// Returns the OS-assigned process identifier associated with this process.
2559///
2560/// # Examples
2561///
2562/// ```no_run
2563/// use std::process;
2564///
2565/// println!("My pid is {}", process::id());
2566/// ```
2567#[must_use]
2568#[stable(feature = "getpid", since = "1.26.0")]
2569pub fn id() -> u32 {
2570    crate::sys::os::getpid()
2571}
2572
2573/// A trait for implementing arbitrary return types in the `main` function.
2574///
2575/// The C-main function only supports returning integers.
2576/// So, every type implementing the `Termination` trait has to be converted
2577/// to an integer.
2578///
2579/// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2580/// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2581///
2582/// Because different runtimes have different specifications on the return value
2583/// of the `main` function, this trait is likely to be available only on
2584/// standard library's runtime for convenience. Other runtimes are not required
2585/// to provide similar functionality.
2586#[cfg_attr(not(any(test, doctest)), lang = "termination")]
2587#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2588#[rustc_on_unimplemented(on(
2589    cause = "MainFunctionType",
2590    message = "`main` has invalid return type `{Self}`",
2591    label = "`main` can only return types that implement `{This}`"
2592))]
2593pub trait Termination {
2594    /// Is called to get the representation of the value as status code.
2595    /// This status code is returned to the operating system.
2596    #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2597    fn report(self) -> ExitCode;
2598}
2599
2600#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2601impl Termination for () {
2602    #[inline]
2603    fn report(self) -> ExitCode {
2604        ExitCode::SUCCESS
2605    }
2606}
2607
2608#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2609impl Termination for ! {
2610    fn report(self) -> ExitCode {
2611        self
2612    }
2613}
2614
2615#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2616impl Termination for Infallible {
2617    fn report(self) -> ExitCode {
2618        match self {}
2619    }
2620}
2621
2622#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2623impl Termination for ExitCode {
2624    #[inline]
2625    fn report(self) -> ExitCode {
2626        self
2627    }
2628}
2629
2630#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2631impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
2632    fn report(self) -> ExitCode {
2633        match self {
2634            Ok(val) => val.report(),
2635            Err(err) => {
2636                io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));
2637                ExitCode::FAILURE
2638            }
2639        }
2640    }
2641}