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