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