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