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