Skip to main content

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