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