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