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