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