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 /// ```
1384 /// #![feature(exit_status_error)]
1385 /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] {
1386 /// use std::process::Command;
1387 /// assert!(Command::new("false").output().unwrap().exit_ok().is_err());
1388 /// # }
1389 /// ```
1390 #[unstable(feature = "exit_status_error", issue = "84908")]
1391 pub fn exit_ok(self) -> Result<Self, ExitStatusError> {
1392 self.status.exit_ok()?;
1393 Ok(self)
1394 }
1395}
1396
1397// If either stderr or stdout are valid utf8 strings it prints the valid
1398// strings, otherwise it prints the byte sequence instead
1399#[stable(feature = "process_output_debug", since = "1.7.0")]
1400impl fmt::Debug for Output {
1401 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1402 let stdout_utf8 = str::from_utf8(&self.stdout);
1403 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1404 Ok(ref s) => s,
1405 Err(_) => &self.stdout,
1406 };
1407
1408 let stderr_utf8 = str::from_utf8(&self.stderr);
1409 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1410 Ok(ref s) => s,
1411 Err(_) => &self.stderr,
1412 };
1413
1414 fmt.debug_struct("Output")
1415 .field("status", &self.status)
1416 .field("stdout", stdout_debug)
1417 .field("stderr", stderr_debug)
1418 .finish()
1419 }
1420}
1421
1422/// Describes what to do with a standard I/O stream for a child process when
1423/// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1424///
1425/// [`stdin`]: Command::stdin
1426/// [`stdout`]: Command::stdout
1427/// [`stderr`]: Command::stderr
1428#[stable(feature = "process", since = "1.0.0")]
1429pub struct Stdio(imp::Stdio);
1430
1431impl Stdio {
1432 /// A new pipe should be arranged to connect the parent and child processes.
1433 ///
1434 /// # Examples
1435 ///
1436 /// With stdout:
1437 ///
1438 /// ```no_run
1439 /// use std::process::{Command, Stdio};
1440 ///
1441 /// let output = Command::new("echo")
1442 /// .arg("Hello, world!")
1443 /// .stdout(Stdio::piped())
1444 /// .output()
1445 /// .expect("Failed to execute command");
1446 ///
1447 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1448 /// // Nothing echoed to console
1449 /// ```
1450 ///
1451 /// With stdin:
1452 ///
1453 /// ```no_run
1454 /// use std::io::Write;
1455 /// use std::process::{Command, Stdio};
1456 ///
1457 /// let mut child = Command::new("rev")
1458 /// .stdin(Stdio::piped())
1459 /// .stdout(Stdio::piped())
1460 /// .spawn()
1461 /// .expect("Failed to spawn child process");
1462 ///
1463 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1464 /// std::thread::spawn(move || {
1465 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1466 /// });
1467 ///
1468 /// let output = child.wait_with_output().expect("Failed to read stdout");
1469 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1470 /// ```
1471 ///
1472 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1473 /// stdout and stderr at the same time may cause a deadlock.
1474 /// This is an issue when running any program that doesn't guarantee that it reads
1475 /// its entire stdin before writing more than a pipe buffer's worth of output.
1476 /// The size of a pipe buffer varies on different targets.
1477 ///
1478 #[must_use]
1479 #[stable(feature = "process", since = "1.0.0")]
1480 pub fn piped() -> Stdio {
1481 Stdio(imp::Stdio::MakePipe)
1482 }
1483
1484 /// The child inherits from the corresponding parent descriptor.
1485 ///
1486 /// # Examples
1487 ///
1488 /// With stdout:
1489 ///
1490 /// ```no_run
1491 /// use std::process::{Command, Stdio};
1492 ///
1493 /// let output = Command::new("echo")
1494 /// .arg("Hello, world!")
1495 /// .stdout(Stdio::inherit())
1496 /// .output()
1497 /// .expect("Failed to execute command");
1498 ///
1499 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1500 /// // "Hello, world!" echoed to console
1501 /// ```
1502 ///
1503 /// With stdin:
1504 ///
1505 /// ```no_run
1506 /// use std::process::{Command, Stdio};
1507 /// use std::io::{self, Write};
1508 ///
1509 /// let output = Command::new("rev")
1510 /// .stdin(Stdio::inherit())
1511 /// .stdout(Stdio::piped())
1512 /// .output()?;
1513 ///
1514 /// print!("You piped in the reverse of: ");
1515 /// io::stdout().write_all(&output.stdout)?;
1516 /// # io::Result::Ok(())
1517 /// ```
1518 #[must_use]
1519 #[stable(feature = "process", since = "1.0.0")]
1520 pub fn inherit() -> Stdio {
1521 Stdio(imp::Stdio::Inherit)
1522 }
1523
1524 /// This stream will be ignored. This is the equivalent of attaching the
1525 /// stream to `/dev/null`.
1526 ///
1527 /// # Examples
1528 ///
1529 /// With stdout:
1530 ///
1531 /// ```no_run
1532 /// use std::process::{Command, Stdio};
1533 ///
1534 /// let output = Command::new("echo")
1535 /// .arg("Hello, world!")
1536 /// .stdout(Stdio::null())
1537 /// .output()
1538 /// .expect("Failed to execute command");
1539 ///
1540 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1541 /// // Nothing echoed to console
1542 /// ```
1543 ///
1544 /// With stdin:
1545 ///
1546 /// ```no_run
1547 /// use std::process::{Command, Stdio};
1548 ///
1549 /// let output = Command::new("rev")
1550 /// .stdin(Stdio::null())
1551 /// .stdout(Stdio::piped())
1552 /// .output()
1553 /// .expect("Failed to execute command");
1554 ///
1555 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1556 /// // Ignores any piped-in input
1557 /// ```
1558 #[must_use]
1559 #[stable(feature = "process", since = "1.0.0")]
1560 pub fn null() -> Stdio {
1561 Stdio(imp::Stdio::Null)
1562 }
1563
1564 /// Returns `true` if this requires [`Command`] to create a new pipe.
1565 ///
1566 /// # Example
1567 ///
1568 /// ```
1569 /// #![feature(stdio_makes_pipe)]
1570 /// use std::process::Stdio;
1571 ///
1572 /// let io = Stdio::piped();
1573 /// assert_eq!(io.makes_pipe(), true);
1574 /// ```
1575 #[unstable(feature = "stdio_makes_pipe", issue = "98288")]
1576 pub fn makes_pipe(&self) -> bool {
1577 matches!(self.0, imp::Stdio::MakePipe)
1578 }
1579}
1580
1581impl FromInner<imp::Stdio> for Stdio {
1582 fn from_inner(inner: imp::Stdio) -> Stdio {
1583 Stdio(inner)
1584 }
1585}
1586
1587#[stable(feature = "std_debug", since = "1.16.0")]
1588impl fmt::Debug for Stdio {
1589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1590 f.debug_struct("Stdio").finish_non_exhaustive()
1591 }
1592}
1593
1594#[stable(feature = "stdio_from", since = "1.20.0")]
1595impl From<ChildStdin> for Stdio {
1596 /// Converts a [`ChildStdin`] into a [`Stdio`].
1597 ///
1598 /// # Examples
1599 ///
1600 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1601 ///
1602 /// ```rust,no_run
1603 /// use std::process::{Command, Stdio};
1604 ///
1605 /// let reverse = Command::new("rev")
1606 /// .stdin(Stdio::piped())
1607 /// .spawn()
1608 /// .expect("failed reverse command");
1609 ///
1610 /// let _echo = Command::new("echo")
1611 /// .arg("Hello, world!")
1612 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1613 /// .output()
1614 /// .expect("failed echo command");
1615 ///
1616 /// // "!dlrow ,olleH" echoed to console
1617 /// ```
1618 fn from(child: ChildStdin) -> Stdio {
1619 Stdio::from_inner(child.into_inner().into())
1620 }
1621}
1622
1623#[stable(feature = "stdio_from", since = "1.20.0")]
1624impl From<ChildStdout> for Stdio {
1625 /// Converts a [`ChildStdout`] into a [`Stdio`].
1626 ///
1627 /// # Examples
1628 ///
1629 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1630 ///
1631 /// ```rust,no_run
1632 /// use std::process::{Command, Stdio};
1633 ///
1634 /// let hello = Command::new("echo")
1635 /// .arg("Hello, world!")
1636 /// .stdout(Stdio::piped())
1637 /// .spawn()
1638 /// .expect("failed echo command");
1639 ///
1640 /// let reverse = Command::new("rev")
1641 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1642 /// .output()
1643 /// .expect("failed reverse command");
1644 ///
1645 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1646 /// ```
1647 fn from(child: ChildStdout) -> Stdio {
1648 Stdio::from_inner(child.into_inner().into())
1649 }
1650}
1651
1652#[stable(feature = "stdio_from", since = "1.20.0")]
1653impl From<ChildStderr> for Stdio {
1654 /// Converts a [`ChildStderr`] into a [`Stdio`].
1655 ///
1656 /// # Examples
1657 ///
1658 /// ```rust,no_run
1659 /// use std::process::{Command, Stdio};
1660 ///
1661 /// let reverse = Command::new("rev")
1662 /// .arg("non_existing_file.txt")
1663 /// .stderr(Stdio::piped())
1664 /// .spawn()
1665 /// .expect("failed reverse command");
1666 ///
1667 /// let cat = Command::new("cat")
1668 /// .arg("-")
1669 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1670 /// .output()
1671 /// .expect("failed echo command");
1672 ///
1673 /// assert_eq!(
1674 /// String::from_utf8_lossy(&cat.stdout),
1675 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1676 /// );
1677 /// ```
1678 fn from(child: ChildStderr) -> Stdio {
1679 Stdio::from_inner(child.into_inner().into())
1680 }
1681}
1682
1683#[stable(feature = "stdio_from", since = "1.20.0")]
1684impl From<fs::File> for Stdio {
1685 /// Converts a [`File`](fs::File) into a [`Stdio`].
1686 ///
1687 /// # Examples
1688 ///
1689 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1690 ///
1691 /// ```rust,no_run
1692 /// use std::fs::File;
1693 /// use std::process::Command;
1694 ///
1695 /// // With the `foo.txt` file containing "Hello, world!"
1696 /// let file = File::open("foo.txt")?;
1697 ///
1698 /// let reverse = Command::new("rev")
1699 /// .stdin(file) // Implicit File conversion into a Stdio
1700 /// .output()?;
1701 ///
1702 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1703 /// # std::io::Result::Ok(())
1704 /// ```
1705 fn from(file: fs::File) -> Stdio {
1706 Stdio::from_inner(file.into_inner().into())
1707 }
1708}
1709
1710#[stable(feature = "stdio_from_stdio", since = "1.74.0")]
1711impl From<io::Stdout> for Stdio {
1712 /// Redirect command stdout/stderr to our stdout
1713 ///
1714 /// # Examples
1715 ///
1716 /// ```rust
1717 /// #![feature(exit_status_error)]
1718 /// use std::io;
1719 /// use std::process::Command;
1720 ///
1721 /// # fn test() -> Result<(), Box<dyn std::error::Error>> {
1722 /// let output = Command::new("whoami")
1723 // "whoami" is a command which exists on both Unix and Windows,
1724 // and which succeeds, producing some stdout output but no stderr.
1725 /// .stdout(io::stdout())
1726 /// .output()?;
1727 /// output.status.exit_ok()?;
1728 /// assert!(output.stdout.is_empty());
1729 /// # Ok(())
1730 /// # }
1731 /// #
1732 /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1733 /// # test().unwrap();
1734 /// # }
1735 /// ```
1736 fn from(inherit: io::Stdout) -> Stdio {
1737 Stdio::from_inner(inherit.into())
1738 }
1739}
1740
1741#[stable(feature = "stdio_from_stdio", since = "1.74.0")]
1742impl From<io::Stderr> for Stdio {
1743 /// Redirect command stdout/stderr to our stderr
1744 ///
1745 /// # Examples
1746 ///
1747 /// ```rust
1748 /// #![feature(exit_status_error)]
1749 /// use std::io;
1750 /// use std::process::Command;
1751 ///
1752 /// # fn test() -> Result<(), Box<dyn std::error::Error>> {
1753 /// let output = Command::new("whoami")
1754 /// .stdout(io::stderr())
1755 /// .output()?;
1756 /// output.status.exit_ok()?;
1757 /// assert!(output.stdout.is_empty());
1758 /// # Ok(())
1759 /// # }
1760 /// #
1761 /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1762 /// # test().unwrap();
1763 /// # }
1764 /// ```
1765 fn from(inherit: io::Stderr) -> Stdio {
1766 Stdio::from_inner(inherit.into())
1767 }
1768}
1769
1770#[stable(feature = "anonymous_pipe", since = "1.87.0")]
1771impl From<io::PipeWriter> for Stdio {
1772 fn from(pipe: io::PipeWriter) -> Self {
1773 Stdio::from_inner(pipe.into_inner().into())
1774 }
1775}
1776
1777#[stable(feature = "anonymous_pipe", since = "1.87.0")]
1778impl From<io::PipeReader> for Stdio {
1779 fn from(pipe: io::PipeReader) -> Self {
1780 Stdio::from_inner(pipe.into_inner().into())
1781 }
1782}
1783
1784/// Describes the result of a process after it has terminated.
1785///
1786/// This `struct` is used to represent the exit status or other termination of a child process.
1787/// Child processes are created via the [`Command`] struct and their exit
1788/// status is exposed through the [`status`] method, or the [`wait`] method
1789/// of a [`Child`] process.
1790///
1791/// An `ExitStatus` represents every possible disposition of a process. On Unix this
1792/// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1793///
1794/// For proper error reporting of failed processes, print the value of `ExitStatus` or
1795/// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1796///
1797/// # Differences from `ExitCode`
1798///
1799/// [`ExitCode`] is intended for terminating the currently running process, via
1800/// the `Termination` trait, in contrast to `ExitStatus`, which represents the
1801/// termination of a child process. These APIs are separate due to platform
1802/// compatibility differences and their expected usage; it is not generally
1803/// possible to exactly reproduce an `ExitStatus` from a child for the current
1804/// process after the fact.
1805///
1806/// [`status`]: Command::status
1807/// [`wait`]: Child::wait
1808//
1809// We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1810// vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1811// matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1812// mean an underlying system call such as `_exit`.
1813#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1814#[stable(feature = "process", since = "1.0.0")]
1815pub struct ExitStatus(imp::ExitStatus);
1816
1817/// The default value is one which indicates successful completion.
1818#[stable(feature = "process_exitstatus_default", since = "1.73.0")]
1819impl Default for ExitStatus {
1820 fn default() -> Self {
1821 // Ideally this would be done by ExitCode::default().into() but that is complicated.
1822 ExitStatus::from_inner(imp::ExitStatus::default())
1823 }
1824}
1825
1826/// Allows extension traits within `std`.
1827#[unstable(feature = "sealed", issue = "none")]
1828impl crate::sealed::Sealed for ExitStatus {}
1829
1830impl ExitStatus {
1831 /// Was termination successful? Returns a `Result`.
1832 ///
1833 /// # Examples
1834 ///
1835 /// ```
1836 /// #![feature(exit_status_error)]
1837 /// # if cfg!(all(unix, not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1838 /// use std::process::Command;
1839 ///
1840 /// let status = Command::new("ls")
1841 /// .arg("/dev/nonexistent")
1842 /// .status()
1843 /// .expect("ls could not be executed");
1844 ///
1845 /// println!("ls: {status}");
1846 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1847 /// # } // cfg!(unix)
1848 /// ```
1849 #[unstable(feature = "exit_status_error", issue = "84908")]
1850 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1851 self.0.exit_ok().map_err(ExitStatusError)
1852 }
1853
1854 /// Was termination successful? Signal termination is not considered a
1855 /// success, and success is defined as a zero exit status.
1856 ///
1857 /// # Examples
1858 ///
1859 /// ```rust,no_run
1860 /// use std::process::Command;
1861 ///
1862 /// let status = Command::new("mkdir")
1863 /// .arg("projects")
1864 /// .status()
1865 /// .expect("failed to execute mkdir");
1866 ///
1867 /// if status.success() {
1868 /// println!("'projects/' directory created");
1869 /// } else {
1870 /// println!("failed to create 'projects/' directory: {status}");
1871 /// }
1872 /// ```
1873 #[must_use]
1874 #[stable(feature = "process", since = "1.0.0")]
1875 pub fn success(&self) -> bool {
1876 self.0.exit_ok().is_ok()
1877 }
1878
1879 /// Returns the exit code of the process, if any.
1880 ///
1881 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1882 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1883 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1884 /// runtime system (often, for example, 255, 254, 127 or 126).
1885 ///
1886 /// On Unix, this will return `None` if the process was terminated by a signal.
1887 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1888 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1889 ///
1890 /// # Examples
1891 ///
1892 /// ```no_run
1893 /// use std::process::Command;
1894 ///
1895 /// let status = Command::new("mkdir")
1896 /// .arg("projects")
1897 /// .status()
1898 /// .expect("failed to execute mkdir");
1899 ///
1900 /// match status.code() {
1901 /// Some(code) => println!("Exited with status code: {code}"),
1902 /// None => println!("Process terminated by signal")
1903 /// }
1904 /// ```
1905 #[must_use]
1906 #[stable(feature = "process", since = "1.0.0")]
1907 pub fn code(&self) -> Option<i32> {
1908 self.0.code()
1909 }
1910}
1911
1912impl AsInner<imp::ExitStatus> for ExitStatus {
1913 #[inline]
1914 fn as_inner(&self) -> &imp::ExitStatus {
1915 &self.0
1916 }
1917}
1918
1919impl FromInner<imp::ExitStatus> for ExitStatus {
1920 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1921 ExitStatus(s)
1922 }
1923}
1924
1925#[stable(feature = "process", since = "1.0.0")]
1926impl fmt::Display for ExitStatus {
1927 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1928 self.0.fmt(f)
1929 }
1930}
1931
1932/// Allows extension traits within `std`.
1933#[unstable(feature = "sealed", issue = "none")]
1934impl crate::sealed::Sealed for ExitStatusError {}
1935
1936/// Describes the result of a process after it has failed
1937///
1938/// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1939///
1940/// # Examples
1941///
1942/// ```
1943/// #![feature(exit_status_error)]
1944/// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1945/// use std::process::{Command, ExitStatusError};
1946///
1947/// fn run(cmd: &str) -> Result<(), ExitStatusError> {
1948/// Command::new(cmd).status().unwrap().exit_ok()?;
1949/// Ok(())
1950/// }
1951///
1952/// run("true").unwrap();
1953/// run("false").unwrap_err();
1954/// # } // cfg!(unix)
1955/// ```
1956#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1957#[unstable(feature = "exit_status_error", issue = "84908")]
1958// The definition of imp::ExitStatusError should ideally be such that
1959// Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1960pub struct ExitStatusError(imp::ExitStatusError);
1961
1962#[unstable(feature = "exit_status_error", issue = "84908")]
1963impl ExitStatusError {
1964 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1965 ///
1966 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1967 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1968 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1969 /// runtime system (often, for example, 255, 254, 127 or 126).
1970 ///
1971 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1972 /// handle such situations specially, consider using methods from
1973 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1974 ///
1975 /// If the process finished by calling `exit` with a nonzero value, this will return
1976 /// that exit status.
1977 ///
1978 /// If the error was something else, it will return `None`.
1979 ///
1980 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1981 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1982 ///
1983 /// # Examples
1984 ///
1985 /// ```
1986 /// #![feature(exit_status_error)]
1987 /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] {
1988 /// use std::process::Command;
1989 ///
1990 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1991 /// assert_eq!(bad.code(), Some(1));
1992 /// # } // #[cfg(unix)]
1993 /// ```
1994 #[must_use]
1995 pub fn code(&self) -> Option<i32> {
1996 self.code_nonzero().map(Into::into)
1997 }
1998
1999 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a [`NonZero`].
2000 ///
2001 /// This is exactly like [`code()`](Self::code), except that it returns a <code>[NonZero]<[i32]></code>.
2002 ///
2003 /// Plain `code`, returning a plain integer, is provided because it is often more convenient.
2004 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
2005 /// a type-level guarantee of nonzeroness.
2006 ///
2007 /// # Examples
2008 ///
2009 /// ```
2010 /// #![feature(exit_status_error)]
2011 ///
2012 /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
2013 /// use std::num::NonZero;
2014 /// use std::process::Command;
2015 ///
2016 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
2017 /// assert_eq!(bad.code_nonzero().unwrap(), NonZero::new(1).unwrap());
2018 /// # } // cfg!(unix)
2019 /// ```
2020 #[must_use]
2021 pub fn code_nonzero(&self) -> Option<NonZero<i32>> {
2022 self.0.code()
2023 }
2024
2025 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
2026 #[must_use]
2027 pub fn into_status(&self) -> ExitStatus {
2028 ExitStatus(self.0.into())
2029 }
2030}
2031
2032#[unstable(feature = "exit_status_error", issue = "84908")]
2033impl From<ExitStatusError> for ExitStatus {
2034 fn from(error: ExitStatusError) -> Self {
2035 Self(error.0.into())
2036 }
2037}
2038
2039#[unstable(feature = "exit_status_error", issue = "84908")]
2040impl fmt::Display for ExitStatusError {
2041 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2042 write!(f, "process exited unsuccessfully: {}", self.into_status())
2043 }
2044}
2045
2046#[unstable(feature = "exit_status_error", issue = "84908")]
2047impl crate::error::Error for ExitStatusError {}
2048
2049/// This type represents the status code the current process can return
2050/// to its parent under normal termination.
2051///
2052/// `ExitCode` is intended to be consumed only by the standard library (via
2053/// [`Termination::report()`]). For forwards compatibility with potentially
2054/// unusual targets, this type currently does not provide `Eq`, `Hash`, or
2055/// access to the raw value. This type does provide `PartialEq` for
2056/// comparison, but note that there may potentially be multiple failure
2057/// codes, some of which will _not_ compare equal to `ExitCode::FAILURE`.
2058/// The standard library provides the canonical `SUCCESS` and `FAILURE`
2059/// exit codes as well as `From<u8> for ExitCode` for constructing other
2060/// arbitrary exit codes.
2061///
2062/// # Portability
2063///
2064/// Numeric values used in this type don't have portable meanings, and
2065/// different platforms may mask different amounts of them.
2066///
2067/// For the platform's canonical successful and unsuccessful codes, see
2068/// the [`SUCCESS`] and [`FAILURE`] associated items.
2069///
2070/// [`SUCCESS`]: ExitCode::SUCCESS
2071/// [`FAILURE`]: ExitCode::FAILURE
2072///
2073/// # Differences from `ExitStatus`
2074///
2075/// `ExitCode` is intended for terminating the currently running process, via
2076/// the `Termination` trait, in contrast to [`ExitStatus`], which represents the
2077/// termination of a child process. These APIs are separate due to platform
2078/// compatibility differences and their expected usage; it is not generally
2079/// possible to exactly reproduce an `ExitStatus` from a child for the current
2080/// process after the fact.
2081///
2082/// # Examples
2083///
2084/// `ExitCode` can be returned from the `main` function of a crate, as it implements
2085/// [`Termination`]:
2086///
2087/// ```
2088/// use std::process::ExitCode;
2089/// # fn check_foo() -> bool { true }
2090///
2091/// fn main() -> ExitCode {
2092/// if !check_foo() {
2093/// return ExitCode::from(42);
2094/// }
2095///
2096/// ExitCode::SUCCESS
2097/// }
2098/// ```
2099#[derive(Clone, Copy, Debug, PartialEq)]
2100#[stable(feature = "process_exitcode", since = "1.61.0")]
2101pub struct ExitCode(imp::ExitCode);
2102
2103/// Allows extension traits within `std`.
2104#[unstable(feature = "sealed", issue = "none")]
2105impl crate::sealed::Sealed for ExitCode {}
2106
2107#[stable(feature = "process_exitcode", since = "1.61.0")]
2108impl ExitCode {
2109 /// The canonical `ExitCode` for successful termination on this platform.
2110 ///
2111 /// Note that a `()`-returning `main` implicitly results in a successful
2112 /// termination, so there's no need to return this from `main` unless
2113 /// you're also returning other possible codes.
2114 #[stable(feature = "process_exitcode", since = "1.61.0")]
2115 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
2116
2117 /// The canonical `ExitCode` for unsuccessful termination on this platform.
2118 ///
2119 /// If you're only returning this and `SUCCESS` from `main`, consider
2120 /// instead returning `Err(_)` and `Ok(())` respectively, which will
2121 /// return the same codes (but will also `eprintln!` the error).
2122 #[stable(feature = "process_exitcode", since = "1.61.0")]
2123 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
2124
2125 /// Exit the current process with the given `ExitCode`.
2126 ///
2127 /// Note that this has the same caveats as [`process::exit()`][exit], namely that this function
2128 /// terminates the process immediately, so no destructors on the current stack or any other
2129 /// thread's stack will be run. Also see those docs for some important notes on interop with C
2130 /// code. If a clean shutdown is needed, it is recommended to simply return this ExitCode from
2131 /// the `main` function, as demonstrated in the [type documentation](#examples).
2132 ///
2133 /// # Differences from `process::exit()`
2134 ///
2135 /// `process::exit()` accepts any `i32` value as the exit code for the process; however, there
2136 /// are platforms that only use a subset of that value (see [`process::exit` platform-specific
2137 /// behavior][exit#platform-specific-behavior]). `ExitCode` exists because of this; only
2138 /// `ExitCode`s that are supported by a majority of our platforms can be created, so those
2139 /// problems don't exist (as much) with this method.
2140 ///
2141 /// # Examples
2142 ///
2143 /// ```
2144 /// #![feature(exitcode_exit_method)]
2145 /// # use std::process::ExitCode;
2146 /// # use std::fmt;
2147 /// # enum UhOhError { GenericProblem, Specific, WithCode { exit_code: ExitCode, _x: () } }
2148 /// # impl fmt::Display for UhOhError {
2149 /// # fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { unimplemented!() }
2150 /// # }
2151 /// // there's no way to gracefully recover from an UhOhError, so we just
2152 /// // print a message and exit
2153 /// fn handle_unrecoverable_error(err: UhOhError) -> ! {
2154 /// eprintln!("UH OH! {err}");
2155 /// let code = match err {
2156 /// UhOhError::GenericProblem => ExitCode::FAILURE,
2157 /// UhOhError::Specific => ExitCode::from(3),
2158 /// UhOhError::WithCode { exit_code, .. } => exit_code,
2159 /// };
2160 /// code.exit_process()
2161 /// }
2162 /// ```
2163 #[unstable(feature = "exitcode_exit_method", issue = "97100")]
2164 pub fn exit_process(self) -> ! {
2165 exit(self.to_i32())
2166 }
2167}
2168
2169impl ExitCode {
2170 // This is private/perma-unstable because ExitCode is opaque; we don't know that i32 will serve
2171 // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
2172 // likely want to isolate users anything that could restrict the platform specific
2173 // representation of an ExitCode
2174 //
2175 // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
2176 /// Converts an `ExitCode` into an i32
2177 #[unstable(
2178 feature = "process_exitcode_internals",
2179 reason = "exposed only for libstd",
2180 issue = "none"
2181 )]
2182 #[inline]
2183 #[doc(hidden)]
2184 pub fn to_i32(self) -> i32 {
2185 self.0.as_i32()
2186 }
2187}
2188
2189/// The default value is [`ExitCode::SUCCESS`]
2190#[stable(feature = "process_exitcode_default", since = "1.75.0")]
2191impl Default for ExitCode {
2192 fn default() -> Self {
2193 ExitCode::SUCCESS
2194 }
2195}
2196
2197#[stable(feature = "process_exitcode", since = "1.61.0")]
2198impl From<u8> for ExitCode {
2199 /// Constructs an `ExitCode` from an arbitrary u8 value.
2200 fn from(code: u8) -> Self {
2201 ExitCode(imp::ExitCode::from(code))
2202 }
2203}
2204
2205impl AsInner<imp::ExitCode> for ExitCode {
2206 #[inline]
2207 fn as_inner(&self) -> &imp::ExitCode {
2208 &self.0
2209 }
2210}
2211
2212impl FromInner<imp::ExitCode> for ExitCode {
2213 fn from_inner(s: imp::ExitCode) -> ExitCode {
2214 ExitCode(s)
2215 }
2216}
2217
2218impl Child {
2219 /// Forces the child process to exit. If the child has already exited, `Ok(())`
2220 /// is returned.
2221 ///
2222 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
2223 ///
2224 /// This is equivalent to sending a SIGKILL on Unix platforms.
2225 ///
2226 /// # Examples
2227 ///
2228 /// ```no_run
2229 /// use std::process::Command;
2230 ///
2231 /// let mut command = Command::new("yes");
2232 /// if let Ok(mut child) = command.spawn() {
2233 /// child.kill().expect("command couldn't be killed");
2234 /// } else {
2235 /// println!("yes command didn't start");
2236 /// }
2237 /// ```
2238 ///
2239 /// [`ErrorKind`]: io::ErrorKind
2240 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
2241 #[stable(feature = "process", since = "1.0.0")]
2242 #[cfg_attr(not(test), rustc_diagnostic_item = "child_kill")]
2243 pub fn kill(&mut self) -> io::Result<()> {
2244 self.handle.kill()
2245 }
2246
2247 /// Returns the OS-assigned process identifier associated with this child.
2248 ///
2249 /// # Examples
2250 ///
2251 /// ```no_run
2252 /// use std::process::Command;
2253 ///
2254 /// let mut command = Command::new("ls");
2255 /// if let Ok(child) = command.spawn() {
2256 /// println!("Child's ID is {}", child.id());
2257 /// } else {
2258 /// println!("ls command didn't start");
2259 /// }
2260 /// ```
2261 #[must_use]
2262 #[stable(feature = "process_id", since = "1.3.0")]
2263 #[cfg_attr(not(test), rustc_diagnostic_item = "child_id")]
2264 pub fn id(&self) -> u32 {
2265 self.handle.id()
2266 }
2267
2268 /// Waits for the child to exit completely, returning the status that it
2269 /// exited with. This function will continue to have the same return value
2270 /// after it has been called at least once.
2271 ///
2272 /// The stdin handle to the child process, if any, will be closed
2273 /// before waiting. This helps avoid deadlock: it ensures that the
2274 /// child does not block waiting for input from the parent, while
2275 /// the parent waits for the child to exit.
2276 ///
2277 /// # Examples
2278 ///
2279 /// ```no_run
2280 /// use std::process::Command;
2281 ///
2282 /// let mut command = Command::new("ls");
2283 /// if let Ok(mut child) = command.spawn() {
2284 /// child.wait().expect("command wasn't running");
2285 /// println!("Child has finished its execution!");
2286 /// } else {
2287 /// println!("ls command didn't start");
2288 /// }
2289 /// ```
2290 #[stable(feature = "process", since = "1.0.0")]
2291 pub fn wait(&mut self) -> io::Result<ExitStatus> {
2292 drop(self.stdin.take());
2293 self.handle.wait().map(ExitStatus)
2294 }
2295
2296 /// Attempts to collect the exit status of the child if it has already
2297 /// exited.
2298 ///
2299 /// This function will not block the calling thread and will only
2300 /// check to see if the child process has exited or not. If the child has
2301 /// exited then on Unix the process ID is reaped. This function is
2302 /// guaranteed to repeatedly return a successful exit status so long as the
2303 /// child has already exited.
2304 ///
2305 /// If the child has exited, then `Ok(Some(status))` is returned. If the
2306 /// exit status is not available at this time then `Ok(None)` is returned.
2307 /// If an error occurs, then that error is returned.
2308 ///
2309 /// Note that unlike `wait`, this function will not attempt to drop stdin.
2310 ///
2311 /// # Examples
2312 ///
2313 /// ```no_run
2314 /// use std::process::Command;
2315 ///
2316 /// let mut child = Command::new("ls").spawn()?;
2317 ///
2318 /// match child.try_wait() {
2319 /// Ok(Some(status)) => println!("exited with: {status}"),
2320 /// Ok(None) => {
2321 /// println!("status not ready yet, let's really wait");
2322 /// let res = child.wait();
2323 /// println!("result: {res:?}");
2324 /// }
2325 /// Err(e) => println!("error attempting to wait: {e}"),
2326 /// }
2327 /// # std::io::Result::Ok(())
2328 /// ```
2329 #[stable(feature = "process_try_wait", since = "1.18.0")]
2330 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
2331 Ok(self.handle.try_wait()?.map(ExitStatus))
2332 }
2333
2334 /// Simultaneously waits for the child to exit and collect all remaining
2335 /// output on the stdout/stderr handles, returning an `Output`
2336 /// instance.
2337 ///
2338 /// The stdin handle to the child process, if any, will be closed
2339 /// before waiting. This helps avoid deadlock: it ensures that the
2340 /// child does not block waiting for input from the parent, while
2341 /// the parent waits for the child to exit.
2342 ///
2343 /// By default, stdin, stdout and stderr are inherited from the parent.
2344 /// In order to capture the output into this `Result<Output>` it is
2345 /// necessary to create new pipes between parent and child. Use
2346 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
2347 ///
2348 /// # Examples
2349 ///
2350 /// ```should_panic
2351 /// use std::process::{Command, Stdio};
2352 ///
2353 /// let child = Command::new("/bin/cat")
2354 /// .arg("file.txt")
2355 /// .stdout(Stdio::piped())
2356 /// .spawn()
2357 /// .expect("failed to execute child");
2358 ///
2359 /// let output = child
2360 /// .wait_with_output()
2361 /// .expect("failed to wait on child");
2362 ///
2363 /// assert!(output.status.success());
2364 /// ```
2365 ///
2366 #[stable(feature = "process", since = "1.0.0")]
2367 pub fn wait_with_output(mut self) -> io::Result<Output> {
2368 drop(self.stdin.take());
2369
2370 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
2371 match (self.stdout.take(), self.stderr.take()) {
2372 (None, None) => {}
2373 (Some(mut out), None) => {
2374 let res = out.read_to_end(&mut stdout);
2375 res.unwrap();
2376 }
2377 (None, Some(mut err)) => {
2378 let res = err.read_to_end(&mut stderr);
2379 res.unwrap();
2380 }
2381 (Some(out), Some(err)) => {
2382 let res = imp::read_output(out.inner, &mut stdout, err.inner, &mut stderr);
2383 res.unwrap();
2384 }
2385 }
2386
2387 let status = self.wait()?;
2388 Ok(Output { status, stdout, stderr })
2389 }
2390}
2391
2392/// Terminates the current process with the specified exit code.
2393///
2394/// This function will never return and will immediately terminate the current
2395/// process. The exit code is passed through to the underlying OS and will be
2396/// available for consumption by another process.
2397///
2398/// Note that because this function never returns, and that it terminates the
2399/// process, no destructors on the current stack or any other thread's stack
2400/// will be run. If a clean shutdown is needed it is recommended to only call
2401/// this function at a known point where there are no more destructors left
2402/// to run; or, preferably, simply return a type implementing [`Termination`]
2403/// (such as [`ExitCode`] or `Result`) from the `main` function and avoid this
2404/// function altogether:
2405///
2406/// ```
2407/// # use std::io::Error as MyError;
2408/// fn main() -> Result<(), MyError> {
2409/// // ...
2410/// Ok(())
2411/// }
2412/// ```
2413///
2414/// In its current implementation, this function will execute exit handlers registered with `atexit`
2415/// as well as other platform-specific exit handlers (e.g. `fini` sections of ELF shared objects).
2416/// This means that Rust requires that all exit handlers are safe to execute at any time. In
2417/// particular, if an exit handler cleans up some state that might be concurrently accessed by other
2418/// threads, it is required that the exit handler performs suitable synchronization with those
2419/// threads. (The alternative to this requirement would be to not run exit handlers at all, which is
2420/// considered undesirable. Note that returning from `main` also calls `exit`, so making `exit` an
2421/// unsafe operation is not an option.)
2422///
2423/// ## Platform-specific behavior
2424///
2425/// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
2426/// will be visible to a parent process inspecting the exit code. On most
2427/// Unix-like platforms, only the eight least-significant bits are considered.
2428///
2429/// For example, the exit code for this example will be `0` on Linux, but `256`
2430/// on Windows:
2431///
2432/// ```no_run
2433/// use std::process;
2434///
2435/// process::exit(0x0100);
2436/// ```
2437///
2438/// ### Safe interop with C code
2439///
2440/// On Unix, this function is currently implemented using the `exit` C function [`exit`][C-exit]. As
2441/// of C23, the C standard does not permit multiple threads to call `exit` concurrently. Rust
2442/// mitigates this with a lock, but if C code calls `exit`, that can still cause undefined behavior.
2443/// Note that returning from `main` is equivalent to calling `exit`.
2444///
2445/// Therefore, it is undefined behavior to have two concurrent threads perform the following
2446/// without synchronization:
2447/// - One thread calls Rust's `exit` function or returns from Rust's `main` function
2448/// - Another thread calls the C function `exit` or `quick_exit`, or returns from C's `main` function
2449///
2450/// Note that if a binary contains multiple copies of the Rust runtime (e.g., when combining
2451/// multiple `cdylib` or `staticlib`), they each have their own separate lock, so from the
2452/// perspective of code running in one of the Rust runtimes, the "outside" Rust code is basically C
2453/// code, and concurrent `exit` again causes undefined behavior.
2454///
2455/// Individual C implementations might provide more guarantees than the standard and permit concurrent
2456/// calls to `exit`; consult the documentation of your C implementation for details.
2457///
2458/// For some of the on-going discussion to make `exit` thread-safe in C, see:
2459/// - [Rust issue #126600](https://github.com/rust-lang/rust/issues/126600)
2460/// - [Austin Group Bugzilla (for POSIX)](https://austingroupbugs.net/view.php?id=1845)
2461/// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=31997)
2462///
2463/// [C-exit]: https://en.cppreference.com/w/c/program/exit
2464#[stable(feature = "rust1", since = "1.0.0")]
2465#[cfg_attr(not(test), rustc_diagnostic_item = "process_exit")]
2466pub fn exit(code: i32) -> ! {
2467 crate::rt::cleanup();
2468 crate::sys::exit::exit(code)
2469}
2470
2471/// Terminates the process in an abnormal fashion.
2472///
2473/// The function will never return and will immediately terminate the current
2474/// process in a platform specific "abnormal" manner. As a consequence,
2475/// no destructors on the current stack or any other thread's stack
2476/// will be run, Rust IO buffers (eg, from `BufWriter`) will not be flushed,
2477/// and C stdio buffers will (on most platforms) not be flushed.
2478///
2479/// This is in contrast to the default behavior of [`panic!`] which unwinds
2480/// the current thread's stack and calls all destructors.
2481/// When `panic="abort"` is set, either as an argument to `rustc` or in a
2482/// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
2483/// [`panic!`] will still call the [panic hook] while `abort` will not.
2484///
2485/// If a clean shutdown is needed it is recommended to only call
2486/// this function at a known point where there are no more destructors left
2487/// to run.
2488///
2489/// The process's termination will be similar to that from the C `abort()`
2490/// function. On Unix, the process will terminate with signal `SIGABRT`, which
2491/// typically means that the shell prints "Aborted".
2492///
2493/// # Examples
2494///
2495/// ```no_run
2496/// use std::process;
2497///
2498/// fn main() {
2499/// println!("aborting");
2500///
2501/// process::abort();
2502///
2503/// // execution never gets here
2504/// }
2505/// ```
2506///
2507/// The `abort` function terminates the process, so the destructor will not
2508/// get run on the example below:
2509///
2510/// ```no_run
2511/// use std::process;
2512///
2513/// struct HasDrop;
2514///
2515/// impl Drop for HasDrop {
2516/// fn drop(&mut self) {
2517/// println!("This will never be printed!");
2518/// }
2519/// }
2520///
2521/// fn main() {
2522/// let _x = HasDrop;
2523/// process::abort();
2524/// // the destructor implemented for HasDrop will never get run
2525/// }
2526/// ```
2527///
2528/// [panic hook]: crate::panic::set_hook
2529#[stable(feature = "process_abort", since = "1.17.0")]
2530#[cold]
2531#[cfg_attr(not(test), rustc_diagnostic_item = "process_abort")]
2532#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2533pub fn abort() -> ! {
2534 crate::sys::abort_internal();
2535}
2536
2537/// Returns the OS-assigned process identifier associated with this process.
2538///
2539/// # Examples
2540///
2541/// ```no_run
2542/// use std::process;
2543///
2544/// println!("My pid is {}", process::id());
2545/// ```
2546#[must_use]
2547#[stable(feature = "getpid", since = "1.26.0")]
2548pub fn id() -> u32 {
2549 imp::getpid()
2550}
2551
2552/// A trait for implementing arbitrary return types in the `main` function.
2553///
2554/// The C-main function only supports returning integers.
2555/// So, every type implementing the `Termination` trait has to be converted
2556/// to an integer.
2557///
2558/// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2559/// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2560///
2561/// Because different runtimes have different specifications on the return value
2562/// of the `main` function, this trait is likely to be available only on
2563/// standard library's runtime for convenience. Other runtimes are not required
2564/// to provide similar functionality.
2565#[cfg_attr(not(any(test, doctest)), lang = "termination")]
2566#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2567#[rustc_on_unimplemented(on(
2568 cause = "MainFunctionType",
2569 message = "`main` has invalid return type `{Self}`",
2570 label = "`main` can only return types that implement `{This}`"
2571))]
2572pub trait Termination {
2573 /// Is called to get the representation of the value as status code.
2574 /// This status code is returned to the operating system.
2575 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2576 fn report(self) -> ExitCode;
2577}
2578
2579#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2580impl Termination for () {
2581 #[inline]
2582 fn report(self) -> ExitCode {
2583 ExitCode::SUCCESS
2584 }
2585}
2586
2587#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2588impl Termination for ! {
2589 fn report(self) -> ExitCode {
2590 self
2591 }
2592}
2593
2594#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2595impl Termination for Infallible {
2596 fn report(self) -> ExitCode {
2597 match self {}
2598 }
2599}
2600
2601#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2602impl Termination for ExitCode {
2603 #[inline]
2604 fn report(self) -> ExitCode {
2605 self
2606 }
2607}
2608
2609#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2610impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
2611 fn report(self) -> ExitCode {
2612 match self {
2613 Ok(val) => val.report(),
2614 Err(err) => {
2615 io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));
2616 ExitCode::FAILURE
2617 }
2618 }
2619 }
2620}