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