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