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