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