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