std/
process.rs

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