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