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 /// ```
1361 /// #![feature(exit_status_error)]
1362 /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] {
1363 /// use std::process::Command;
1364 /// assert!(Command::new("false").output().unwrap().exit_ok().is_err());
1365 /// # }
1366 /// ```
1367 #[unstable(feature = "exit_status_error", issue = "84908")]
1368 pub fn exit_ok(self) -> Result<Self, ExitStatusError> {
1369 self.status.exit_ok()?;
1370 Ok(self)
1371 }
1372}
1373
1374// If either stderr or stdout are valid utf8 strings it prints the valid
1375// strings, otherwise it prints the byte sequence instead
1376#[stable(feature = "process_output_debug", since = "1.7.0")]
1377impl fmt::Debug for Output {
1378 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1379 let stdout_utf8 = str::from_utf8(&self.stdout);
1380 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1381 Ok(ref s) => s,
1382 Err(_) => &self.stdout,
1383 };
1384
1385 let stderr_utf8 = str::from_utf8(&self.stderr);
1386 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1387 Ok(ref s) => s,
1388 Err(_) => &self.stderr,
1389 };
1390
1391 fmt.debug_struct("Output")
1392 .field("status", &self.status)
1393 .field("stdout", stdout_debug)
1394 .field("stderr", stderr_debug)
1395 .finish()
1396 }
1397}
1398
1399/// Describes what to do with a standard I/O stream for a child process when
1400/// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1401///
1402/// [`stdin`]: Command::stdin
1403/// [`stdout`]: Command::stdout
1404/// [`stderr`]: Command::stderr
1405#[stable(feature = "process", since = "1.0.0")]
1406pub struct Stdio(imp::Stdio);
1407
1408impl Stdio {
1409 /// A new pipe should be arranged to connect the parent and child processes.
1410 ///
1411 /// # Examples
1412 ///
1413 /// With stdout:
1414 ///
1415 /// ```no_run
1416 /// use std::process::{Command, Stdio};
1417 ///
1418 /// let output = Command::new("echo")
1419 /// .arg("Hello, world!")
1420 /// .stdout(Stdio::piped())
1421 /// .output()
1422 /// .expect("Failed to execute command");
1423 ///
1424 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1425 /// // Nothing echoed to console
1426 /// ```
1427 ///
1428 /// With stdin:
1429 ///
1430 /// ```no_run
1431 /// use std::io::Write;
1432 /// use std::process::{Command, Stdio};
1433 ///
1434 /// let mut child = Command::new("rev")
1435 /// .stdin(Stdio::piped())
1436 /// .stdout(Stdio::piped())
1437 /// .spawn()
1438 /// .expect("Failed to spawn child process");
1439 ///
1440 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1441 /// std::thread::spawn(move || {
1442 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1443 /// });
1444 ///
1445 /// let output = child.wait_with_output().expect("Failed to read stdout");
1446 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1447 /// ```
1448 ///
1449 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1450 /// stdout and stderr at the same time may cause a deadlock.
1451 /// This is an issue when running any program that doesn't guarantee that it reads
1452 /// its entire stdin before writing more than a pipe buffer's worth of output.
1453 /// The size of a pipe buffer varies on different targets.
1454 ///
1455 #[must_use]
1456 #[stable(feature = "process", since = "1.0.0")]
1457 pub fn piped() -> Stdio {
1458 Stdio(imp::Stdio::MakePipe)
1459 }
1460
1461 /// The child inherits from the corresponding parent descriptor.
1462 ///
1463 /// # Examples
1464 ///
1465 /// With stdout:
1466 ///
1467 /// ```no_run
1468 /// use std::process::{Command, Stdio};
1469 ///
1470 /// let output = Command::new("echo")
1471 /// .arg("Hello, world!")
1472 /// .stdout(Stdio::inherit())
1473 /// .output()
1474 /// .expect("Failed to execute command");
1475 ///
1476 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1477 /// // "Hello, world!" echoed to console
1478 /// ```
1479 ///
1480 /// With stdin:
1481 ///
1482 /// ```no_run
1483 /// use std::process::{Command, Stdio};
1484 /// use std::io::{self, Write};
1485 ///
1486 /// let output = Command::new("rev")
1487 /// .stdin(Stdio::inherit())
1488 /// .stdout(Stdio::piped())
1489 /// .output()?;
1490 ///
1491 /// print!("You piped in the reverse of: ");
1492 /// io::stdout().write_all(&output.stdout)?;
1493 /// # io::Result::Ok(())
1494 /// ```
1495 #[must_use]
1496 #[stable(feature = "process", since = "1.0.0")]
1497 pub fn inherit() -> Stdio {
1498 Stdio(imp::Stdio::Inherit)
1499 }
1500
1501 /// This stream will be ignored. This is the equivalent of attaching the
1502 /// stream to `/dev/null`.
1503 ///
1504 /// # Examples
1505 ///
1506 /// With stdout:
1507 ///
1508 /// ```no_run
1509 /// use std::process::{Command, Stdio};
1510 ///
1511 /// let output = Command::new("echo")
1512 /// .arg("Hello, world!")
1513 /// .stdout(Stdio::null())
1514 /// .output()
1515 /// .expect("Failed to execute command");
1516 ///
1517 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1518 /// // Nothing echoed to console
1519 /// ```
1520 ///
1521 /// With stdin:
1522 ///
1523 /// ```no_run
1524 /// use std::process::{Command, Stdio};
1525 ///
1526 /// let output = Command::new("rev")
1527 /// .stdin(Stdio::null())
1528 /// .stdout(Stdio::piped())
1529 /// .output()
1530 /// .expect("Failed to execute command");
1531 ///
1532 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1533 /// // Ignores any piped-in input
1534 /// ```
1535 #[must_use]
1536 #[stable(feature = "process", since = "1.0.0")]
1537 pub fn null() -> Stdio {
1538 Stdio(imp::Stdio::Null)
1539 }
1540
1541 /// Returns `true` if this requires [`Command`] to create a new pipe.
1542 ///
1543 /// # Example
1544 ///
1545 /// ```
1546 /// #![feature(stdio_makes_pipe)]
1547 /// use std::process::Stdio;
1548 ///
1549 /// let io = Stdio::piped();
1550 /// assert_eq!(io.makes_pipe(), true);
1551 /// ```
1552 #[unstable(feature = "stdio_makes_pipe", issue = "98288")]
1553 pub fn makes_pipe(&self) -> bool {
1554 matches!(self.0, imp::Stdio::MakePipe)
1555 }
1556}
1557
1558impl FromInner<imp::Stdio> for Stdio {
1559 fn from_inner(inner: imp::Stdio) -> Stdio {
1560 Stdio(inner)
1561 }
1562}
1563
1564#[stable(feature = "std_debug", since = "1.16.0")]
1565impl fmt::Debug for Stdio {
1566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1567 f.debug_struct("Stdio").finish_non_exhaustive()
1568 }
1569}
1570
1571#[stable(feature = "stdio_from", since = "1.20.0")]
1572impl From<ChildStdin> for Stdio {
1573 /// Converts a [`ChildStdin`] into a [`Stdio`].
1574 ///
1575 /// # Examples
1576 ///
1577 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1578 ///
1579 /// ```rust,no_run
1580 /// use std::process::{Command, Stdio};
1581 ///
1582 /// let reverse = Command::new("rev")
1583 /// .stdin(Stdio::piped())
1584 /// .spawn()
1585 /// .expect("failed reverse command");
1586 ///
1587 /// let _echo = Command::new("echo")
1588 /// .arg("Hello, world!")
1589 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1590 /// .output()
1591 /// .expect("failed echo command");
1592 ///
1593 /// // "!dlrow ,olleH" echoed to console
1594 /// ```
1595 fn from(child: ChildStdin) -> Stdio {
1596 Stdio::from_inner(child.into_inner().into())
1597 }
1598}
1599
1600#[stable(feature = "stdio_from", since = "1.20.0")]
1601impl From<ChildStdout> for Stdio {
1602 /// Converts a [`ChildStdout`] into a [`Stdio`].
1603 ///
1604 /// # Examples
1605 ///
1606 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1607 ///
1608 /// ```rust,no_run
1609 /// use std::process::{Command, Stdio};
1610 ///
1611 /// let hello = Command::new("echo")
1612 /// .arg("Hello, world!")
1613 /// .stdout(Stdio::piped())
1614 /// .spawn()
1615 /// .expect("failed echo command");
1616 ///
1617 /// let reverse = Command::new("rev")
1618 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1619 /// .output()
1620 /// .expect("failed reverse command");
1621 ///
1622 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1623 /// ```
1624 fn from(child: ChildStdout) -> Stdio {
1625 Stdio::from_inner(child.into_inner().into())
1626 }
1627}
1628
1629#[stable(feature = "stdio_from", since = "1.20.0")]
1630impl From<ChildStderr> for Stdio {
1631 /// Converts a [`ChildStderr`] into a [`Stdio`].
1632 ///
1633 /// # Examples
1634 ///
1635 /// ```rust,no_run
1636 /// use std::process::{Command, Stdio};
1637 ///
1638 /// let reverse = Command::new("rev")
1639 /// .arg("non_existing_file.txt")
1640 /// .stderr(Stdio::piped())
1641 /// .spawn()
1642 /// .expect("failed reverse command");
1643 ///
1644 /// let cat = Command::new("cat")
1645 /// .arg("-")
1646 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1647 /// .output()
1648 /// .expect("failed echo command");
1649 ///
1650 /// assert_eq!(
1651 /// String::from_utf8_lossy(&cat.stdout),
1652 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1653 /// );
1654 /// ```
1655 fn from(child: ChildStderr) -> Stdio {
1656 Stdio::from_inner(child.into_inner().into())
1657 }
1658}
1659
1660#[stable(feature = "stdio_from", since = "1.20.0")]
1661impl From<fs::File> for Stdio {
1662 /// Converts a [`File`](fs::File) into a [`Stdio`].
1663 ///
1664 /// # Examples
1665 ///
1666 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1667 ///
1668 /// ```rust,no_run
1669 /// use std::fs::File;
1670 /// use std::process::Command;
1671 ///
1672 /// // With the `foo.txt` file containing "Hello, world!"
1673 /// let file = File::open("foo.txt")?;
1674 ///
1675 /// let reverse = Command::new("rev")
1676 /// .stdin(file) // Implicit File conversion into a Stdio
1677 /// .output()?;
1678 ///
1679 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1680 /// # std::io::Result::Ok(())
1681 /// ```
1682 fn from(file: fs::File) -> Stdio {
1683 Stdio::from_inner(file.into_inner().into())
1684 }
1685}
1686
1687#[stable(feature = "stdio_from_stdio", since = "1.74.0")]
1688impl From<io::Stdout> for Stdio {
1689 /// Redirect command stdout/stderr to our stdout
1690 ///
1691 /// # Examples
1692 ///
1693 /// ```rust
1694 /// #![feature(exit_status_error)]
1695 /// use std::io;
1696 /// use std::process::Command;
1697 ///
1698 /// # fn test() -> Result<(), Box<dyn std::error::Error>> {
1699 /// let output = Command::new("whoami")
1700 // "whoami" is a command which exists on both Unix and Windows,
1701 // and which succeeds, producing some stdout output but no stderr.
1702 /// .stdout(io::stdout())
1703 /// .output()?;
1704 /// output.status.exit_ok()?;
1705 /// assert!(output.stdout.is_empty());
1706 /// # Ok(())
1707 /// # }
1708 /// #
1709 /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1710 /// # test().unwrap();
1711 /// # }
1712 /// ```
1713 fn from(inherit: io::Stdout) -> Stdio {
1714 Stdio::from_inner(inherit.into())
1715 }
1716}
1717
1718#[stable(feature = "stdio_from_stdio", since = "1.74.0")]
1719impl From<io::Stderr> for Stdio {
1720 /// Redirect command stdout/stderr to our stderr
1721 ///
1722 /// # Examples
1723 ///
1724 /// ```rust
1725 /// #![feature(exit_status_error)]
1726 /// use std::io;
1727 /// use std::process::Command;
1728 ///
1729 /// # fn test() -> Result<(), Box<dyn std::error::Error>> {
1730 /// let output = Command::new("whoami")
1731 /// .stdout(io::stderr())
1732 /// .output()?;
1733 /// output.status.exit_ok()?;
1734 /// assert!(output.stdout.is_empty());
1735 /// # Ok(())
1736 /// # }
1737 /// #
1738 /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1739 /// # test().unwrap();
1740 /// # }
1741 /// ```
1742 fn from(inherit: io::Stderr) -> Stdio {
1743 Stdio::from_inner(inherit.into())
1744 }
1745}
1746
1747#[stable(feature = "anonymous_pipe", since = "1.87.0")]
1748impl From<io::PipeWriter> for Stdio {
1749 fn from(pipe: io::PipeWriter) -> Self {
1750 Stdio::from_inner(pipe.into_inner().into())
1751 }
1752}
1753
1754#[stable(feature = "anonymous_pipe", since = "1.87.0")]
1755impl From<io::PipeReader> for Stdio {
1756 fn from(pipe: io::PipeReader) -> Self {
1757 Stdio::from_inner(pipe.into_inner().into())
1758 }
1759}
1760
1761/// Describes the result of a process after it has terminated.
1762///
1763/// This `struct` is used to represent the exit status or other termination of a child process.
1764/// Child processes are created via the [`Command`] struct and their exit
1765/// status is exposed through the [`status`] method, or the [`wait`] method
1766/// of a [`Child`] process.
1767///
1768/// An `ExitStatus` represents every possible disposition of a process. On Unix this
1769/// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1770///
1771/// For proper error reporting of failed processes, print the value of `ExitStatus` or
1772/// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1773///
1774/// # Differences from `ExitCode`
1775///
1776/// [`ExitCode`] is intended for terminating the currently running process, via
1777/// the `Termination` trait, in contrast to `ExitStatus`, which represents the
1778/// termination of a child process. These APIs are separate due to platform
1779/// compatibility differences and their expected usage; it is not generally
1780/// possible to exactly reproduce an `ExitStatus` from a child for the current
1781/// process after the fact.
1782///
1783/// [`status`]: Command::status
1784/// [`wait`]: Child::wait
1785//
1786// We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1787// vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1788// matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1789// mean an underlying system call such as `_exit`.
1790#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1791#[stable(feature = "process", since = "1.0.0")]
1792pub struct ExitStatus(imp::ExitStatus);
1793
1794/// The default value is one which indicates successful completion.
1795#[stable(feature = "process_exitstatus_default", since = "1.73.0")]
1796impl Default for ExitStatus {
1797 fn default() -> Self {
1798 // Ideally this would be done by ExitCode::default().into() but that is complicated.
1799 ExitStatus::from_inner(imp::ExitStatus::default())
1800 }
1801}
1802
1803/// Allows extension traits within `std`.
1804#[unstable(feature = "sealed", issue = "none")]
1805impl crate::sealed::Sealed for ExitStatus {}
1806
1807impl ExitStatus {
1808 /// Was termination successful? Returns a `Result`.
1809 ///
1810 /// # Examples
1811 ///
1812 /// ```
1813 /// #![feature(exit_status_error)]
1814 /// # if cfg!(all(unix, not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1815 /// use std::process::Command;
1816 ///
1817 /// let status = Command::new("ls")
1818 /// .arg("/dev/nonexistent")
1819 /// .status()
1820 /// .expect("ls could not be executed");
1821 ///
1822 /// println!("ls: {status}");
1823 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1824 /// # } // cfg!(unix)
1825 /// ```
1826 #[unstable(feature = "exit_status_error", issue = "84908")]
1827 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1828 self.0.exit_ok().map_err(ExitStatusError)
1829 }
1830
1831 /// Was termination successful? Signal termination is not considered a
1832 /// success, and success is defined as a zero exit status.
1833 ///
1834 /// # Examples
1835 ///
1836 /// ```rust,no_run
1837 /// use std::process::Command;
1838 ///
1839 /// let status = Command::new("mkdir")
1840 /// .arg("projects")
1841 /// .status()
1842 /// .expect("failed to execute mkdir");
1843 ///
1844 /// if status.success() {
1845 /// println!("'projects/' directory created");
1846 /// } else {
1847 /// println!("failed to create 'projects/' directory: {status}");
1848 /// }
1849 /// ```
1850 #[must_use]
1851 #[stable(feature = "process", since = "1.0.0")]
1852 pub fn success(&self) -> bool {
1853 self.0.exit_ok().is_ok()
1854 }
1855
1856 /// Returns the exit code of the process, if any.
1857 ///
1858 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1859 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1860 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1861 /// runtime system (often, for example, 255, 254, 127 or 126).
1862 ///
1863 /// On Unix, this will return `None` if the process was terminated by a signal.
1864 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1865 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1866 ///
1867 /// # Examples
1868 ///
1869 /// ```no_run
1870 /// use std::process::Command;
1871 ///
1872 /// let status = Command::new("mkdir")
1873 /// .arg("projects")
1874 /// .status()
1875 /// .expect("failed to execute mkdir");
1876 ///
1877 /// match status.code() {
1878 /// Some(code) => println!("Exited with status code: {code}"),
1879 /// None => println!("Process terminated by signal")
1880 /// }
1881 /// ```
1882 #[must_use]
1883 #[stable(feature = "process", since = "1.0.0")]
1884 pub fn code(&self) -> Option<i32> {
1885 self.0.code()
1886 }
1887}
1888
1889impl AsInner<imp::ExitStatus> for ExitStatus {
1890 #[inline]
1891 fn as_inner(&self) -> &imp::ExitStatus {
1892 &self.0
1893 }
1894}
1895
1896impl FromInner<imp::ExitStatus> for ExitStatus {
1897 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1898 ExitStatus(s)
1899 }
1900}
1901
1902#[stable(feature = "process", since = "1.0.0")]
1903impl fmt::Display for ExitStatus {
1904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1905 self.0.fmt(f)
1906 }
1907}
1908
1909/// Allows extension traits within `std`.
1910#[unstable(feature = "sealed", issue = "none")]
1911impl crate::sealed::Sealed for ExitStatusError {}
1912
1913/// Describes the result of a process after it has failed
1914///
1915/// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1916///
1917/// # Examples
1918///
1919/// ```
1920/// #![feature(exit_status_error)]
1921/// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1922/// use std::process::{Command, ExitStatusError};
1923///
1924/// fn run(cmd: &str) -> Result<(), ExitStatusError> {
1925/// Command::new(cmd).status().unwrap().exit_ok()?;
1926/// Ok(())
1927/// }
1928///
1929/// run("true").unwrap();
1930/// run("false").unwrap_err();
1931/// # } // cfg!(unix)
1932/// ```
1933#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1934#[unstable(feature = "exit_status_error", issue = "84908")]
1935// The definition of imp::ExitStatusError should ideally be such that
1936// Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1937pub struct ExitStatusError(imp::ExitStatusError);
1938
1939#[unstable(feature = "exit_status_error", issue = "84908")]
1940impl ExitStatusError {
1941 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1942 ///
1943 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1944 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1945 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1946 /// runtime system (often, for example, 255, 254, 127 or 126).
1947 ///
1948 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1949 /// handle such situations specially, consider using methods from
1950 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1951 ///
1952 /// If the process finished by calling `exit` with a nonzero value, this will return
1953 /// that exit status.
1954 ///
1955 /// If the error was something else, it will return `None`.
1956 ///
1957 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1958 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1959 ///
1960 /// # Examples
1961 ///
1962 /// ```
1963 /// #![feature(exit_status_error)]
1964 /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] {
1965 /// use std::process::Command;
1966 ///
1967 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1968 /// assert_eq!(bad.code(), Some(1));
1969 /// # } // #[cfg(unix)]
1970 /// ```
1971 #[must_use]
1972 pub fn code(&self) -> Option<i32> {
1973 self.code_nonzero().map(Into::into)
1974 }
1975
1976 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a [`NonZero`].
1977 ///
1978 /// This is exactly like [`code()`](Self::code), except that it returns a <code>[NonZero]<[i32]></code>.
1979 ///
1980 /// Plain `code`, returning a plain integer, is provided because it is often more convenient.
1981 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1982 /// a type-level guarantee of nonzeroness.
1983 ///
1984 /// # Examples
1985 ///
1986 /// ```
1987 /// #![feature(exit_status_error)]
1988 ///
1989 /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) {
1990 /// use std::num::NonZero;
1991 /// use std::process::Command;
1992 ///
1993 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1994 /// assert_eq!(bad.code_nonzero().unwrap(), NonZero::new(1).unwrap());
1995 /// # } // cfg!(unix)
1996 /// ```
1997 #[must_use]
1998 pub fn code_nonzero(&self) -> Option<NonZero<i32>> {
1999 self.0.code()
2000 }
2001
2002 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
2003 #[must_use]
2004 pub fn into_status(&self) -> ExitStatus {
2005 ExitStatus(self.0.into())
2006 }
2007}
2008
2009#[unstable(feature = "exit_status_error", issue = "84908")]
2010impl From<ExitStatusError> for ExitStatus {
2011 fn from(error: ExitStatusError) -> Self {
2012 Self(error.0.into())
2013 }
2014}
2015
2016#[unstable(feature = "exit_status_error", issue = "84908")]
2017impl fmt::Display for ExitStatusError {
2018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2019 write!(f, "process exited unsuccessfully: {}", self.into_status())
2020 }
2021}
2022
2023#[unstable(feature = "exit_status_error", issue = "84908")]
2024impl crate::error::Error for ExitStatusError {}
2025
2026/// This type represents the status code the current process can return
2027/// to its parent under normal termination.
2028///
2029/// `ExitCode` is intended to be consumed only by the standard library (via
2030/// [`Termination::report()`]). For forwards compatibility with potentially
2031/// unusual targets, this type currently does not provide `Eq`, `Hash`, or
2032/// access to the raw value. This type does provide `PartialEq` for
2033/// comparison, but note that there may potentially be multiple failure
2034/// codes, some of which will _not_ compare equal to `ExitCode::FAILURE`.
2035/// The standard library provides the canonical `SUCCESS` and `FAILURE`
2036/// exit codes as well as `From<u8> for ExitCode` for constructing other
2037/// arbitrary exit codes.
2038///
2039/// # Portability
2040///
2041/// Numeric values used in this type don't have portable meanings, and
2042/// different platforms may mask different amounts of them.
2043///
2044/// For the platform's canonical successful and unsuccessful codes, see
2045/// the [`SUCCESS`] and [`FAILURE`] associated items.
2046///
2047/// [`SUCCESS`]: ExitCode::SUCCESS
2048/// [`FAILURE`]: ExitCode::FAILURE
2049///
2050/// # Differences from `ExitStatus`
2051///
2052/// `ExitCode` is intended for terminating the currently running process, via
2053/// the `Termination` trait, in contrast to [`ExitStatus`], which represents the
2054/// termination of a child process. These APIs are separate due to platform
2055/// compatibility differences and their expected usage; it is not generally
2056/// possible to exactly reproduce an `ExitStatus` from a child for the current
2057/// process after the fact.
2058///
2059/// # Examples
2060///
2061/// `ExitCode` can be returned from the `main` function of a crate, as it implements
2062/// [`Termination`]:
2063///
2064/// ```
2065/// use std::process::ExitCode;
2066/// # fn check_foo() -> bool { true }
2067///
2068/// fn main() -> ExitCode {
2069/// if !check_foo() {
2070/// return ExitCode::from(42);
2071/// }
2072///
2073/// ExitCode::SUCCESS
2074/// }
2075/// ```
2076#[derive(Clone, Copy, Debug, PartialEq)]
2077#[stable(feature = "process_exitcode", since = "1.61.0")]
2078pub struct ExitCode(imp::ExitCode);
2079
2080/// Allows extension traits within `std`.
2081#[unstable(feature = "sealed", issue = "none")]
2082impl crate::sealed::Sealed for ExitCode {}
2083
2084#[stable(feature = "process_exitcode", since = "1.61.0")]
2085impl ExitCode {
2086 /// The canonical `ExitCode` for successful termination on this platform.
2087 ///
2088 /// Note that a `()`-returning `main` implicitly results in a successful
2089 /// termination, so there's no need to return this from `main` unless
2090 /// you're also returning other possible codes.
2091 #[stable(feature = "process_exitcode", since = "1.61.0")]
2092 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
2093
2094 /// The canonical `ExitCode` for unsuccessful termination on this platform.
2095 ///
2096 /// If you're only returning this and `SUCCESS` from `main`, consider
2097 /// instead returning `Err(_)` and `Ok(())` respectively, which will
2098 /// return the same codes (but will also `eprintln!` the error).
2099 #[stable(feature = "process_exitcode", since = "1.61.0")]
2100 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
2101
2102 /// Exit the current process with the given `ExitCode`.
2103 ///
2104 /// Note that this has the same caveats as [`process::exit()`][exit], namely that this function
2105 /// terminates the process immediately, so no destructors on the current stack or any other
2106 /// thread's stack will be run. Also see those docs for some important notes on interop with C
2107 /// code. If a clean shutdown is needed, it is recommended to simply return this ExitCode from
2108 /// the `main` function, as demonstrated in the [type documentation](#examples).
2109 ///
2110 /// # Differences from `process::exit()`
2111 ///
2112 /// `process::exit()` accepts any `i32` value as the exit code for the process; however, there
2113 /// are platforms that only use a subset of that value (see [`process::exit` platform-specific
2114 /// behavior][exit#platform-specific-behavior]). `ExitCode` exists because of this; only
2115 /// `ExitCode`s that are supported by a majority of our platforms can be created, so those
2116 /// problems don't exist (as much) with this method.
2117 ///
2118 /// # Examples
2119 ///
2120 /// ```
2121 /// #![feature(exitcode_exit_method)]
2122 /// # use std::process::ExitCode;
2123 /// # use std::fmt;
2124 /// # enum UhOhError { GenericProblem, Specific, WithCode { exit_code: ExitCode, _x: () } }
2125 /// # impl fmt::Display for UhOhError {
2126 /// # fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { unimplemented!() }
2127 /// # }
2128 /// // there's no way to gracefully recover from an UhOhError, so we just
2129 /// // print a message and exit
2130 /// fn handle_unrecoverable_error(err: UhOhError) -> ! {
2131 /// eprintln!("UH OH! {err}");
2132 /// let code = match err {
2133 /// UhOhError::GenericProblem => ExitCode::FAILURE,
2134 /// UhOhError::Specific => ExitCode::from(3),
2135 /// UhOhError::WithCode { exit_code, .. } => exit_code,
2136 /// };
2137 /// code.exit_process()
2138 /// }
2139 /// ```
2140 #[unstable(feature = "exitcode_exit_method", issue = "97100")]
2141 pub fn exit_process(self) -> ! {
2142 exit(self.to_i32())
2143 }
2144}
2145
2146impl ExitCode {
2147 // This is private/perma-unstable because ExitCode is opaque; we don't know that i32 will serve
2148 // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
2149 // likely want to isolate users anything that could restrict the platform specific
2150 // representation of an ExitCode
2151 //
2152 // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
2153 /// Converts an `ExitCode` into an i32
2154 #[unstable(
2155 feature = "process_exitcode_internals",
2156 reason = "exposed only for libstd",
2157 issue = "none"
2158 )]
2159 #[inline]
2160 #[doc(hidden)]
2161 pub fn to_i32(self) -> i32 {
2162 self.0.as_i32()
2163 }
2164}
2165
2166/// The default value is [`ExitCode::SUCCESS`]
2167#[stable(feature = "process_exitcode_default", since = "1.75.0")]
2168impl Default for ExitCode {
2169 fn default() -> Self {
2170 ExitCode::SUCCESS
2171 }
2172}
2173
2174#[stable(feature = "process_exitcode", since = "1.61.0")]
2175impl From<u8> for ExitCode {
2176 /// Constructs an `ExitCode` from an arbitrary u8 value.
2177 fn from(code: u8) -> Self {
2178 ExitCode(imp::ExitCode::from(code))
2179 }
2180}
2181
2182impl AsInner<imp::ExitCode> for ExitCode {
2183 #[inline]
2184 fn as_inner(&self) -> &imp::ExitCode {
2185 &self.0
2186 }
2187}
2188
2189impl FromInner<imp::ExitCode> for ExitCode {
2190 fn from_inner(s: imp::ExitCode) -> ExitCode {
2191 ExitCode(s)
2192 }
2193}
2194
2195impl Child {
2196 /// Forces the child process to exit. If the child has already exited, `Ok(())`
2197 /// is returned.
2198 ///
2199 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
2200 ///
2201 /// This is equivalent to sending a SIGKILL on Unix platforms.
2202 ///
2203 /// # Examples
2204 ///
2205 /// ```no_run
2206 /// use std::process::Command;
2207 ///
2208 /// let mut command = Command::new("yes");
2209 /// if let Ok(mut child) = command.spawn() {
2210 /// child.kill().expect("command couldn't be killed");
2211 /// } else {
2212 /// println!("yes command didn't start");
2213 /// }
2214 /// ```
2215 ///
2216 /// [`ErrorKind`]: io::ErrorKind
2217 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
2218 #[stable(feature = "process", since = "1.0.0")]
2219 #[cfg_attr(not(test), rustc_diagnostic_item = "child_kill")]
2220 pub fn kill(&mut self) -> io::Result<()> {
2221 self.handle.kill()
2222 }
2223
2224 /// Returns the OS-assigned process identifier associated with this child.
2225 ///
2226 /// # Examples
2227 ///
2228 /// ```no_run
2229 /// use std::process::Command;
2230 ///
2231 /// let mut command = Command::new("ls");
2232 /// if let Ok(child) = command.spawn() {
2233 /// println!("Child's ID is {}", child.id());
2234 /// } else {
2235 /// println!("ls command didn't start");
2236 /// }
2237 /// ```
2238 #[must_use]
2239 #[stable(feature = "process_id", since = "1.3.0")]
2240 #[cfg_attr(not(test), rustc_diagnostic_item = "child_id")]
2241 pub fn id(&self) -> u32 {
2242 self.handle.id()
2243 }
2244
2245 /// Waits for the child to exit completely, returning the status that it
2246 /// exited with. This function will continue to have the same return value
2247 /// after it has been called at least once.
2248 ///
2249 /// The stdin handle to the child process, if any, will be closed
2250 /// before waiting. This helps avoid deadlock: it ensures that the
2251 /// child does not block waiting for input from the parent, while
2252 /// the parent waits for the child to exit.
2253 ///
2254 /// # Examples
2255 ///
2256 /// ```no_run
2257 /// use std::process::Command;
2258 ///
2259 /// let mut command = Command::new("ls");
2260 /// if let Ok(mut child) = command.spawn() {
2261 /// child.wait().expect("command wasn't running");
2262 /// println!("Child has finished its execution!");
2263 /// } else {
2264 /// println!("ls command didn't start");
2265 /// }
2266 /// ```
2267 #[stable(feature = "process", since = "1.0.0")]
2268 pub fn wait(&mut self) -> io::Result<ExitStatus> {
2269 drop(self.stdin.take());
2270 self.handle.wait().map(ExitStatus)
2271 }
2272
2273 /// Attempts to collect the exit status of the child if it has already
2274 /// exited.
2275 ///
2276 /// This function will not block the calling thread and will only
2277 /// check to see if the child process has exited or not. If the child has
2278 /// exited then on Unix the process ID is reaped. This function is
2279 /// guaranteed to repeatedly return a successful exit status so long as the
2280 /// child has already exited.
2281 ///
2282 /// If the child has exited, then `Ok(Some(status))` is returned. If the
2283 /// exit status is not available at this time then `Ok(None)` is returned.
2284 /// If an error occurs, then that error is returned.
2285 ///
2286 /// Note that unlike `wait`, this function will not attempt to drop stdin.
2287 ///
2288 /// # Examples
2289 ///
2290 /// ```no_run
2291 /// use std::process::Command;
2292 ///
2293 /// let mut child = Command::new("ls").spawn()?;
2294 ///
2295 /// match child.try_wait() {
2296 /// Ok(Some(status)) => println!("exited with: {status}"),
2297 /// Ok(None) => {
2298 /// println!("status not ready yet, let's really wait");
2299 /// let res = child.wait();
2300 /// println!("result: {res:?}");
2301 /// }
2302 /// Err(e) => println!("error attempting to wait: {e}"),
2303 /// }
2304 /// # std::io::Result::Ok(())
2305 /// ```
2306 #[stable(feature = "process_try_wait", since = "1.18.0")]
2307 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
2308 Ok(self.handle.try_wait()?.map(ExitStatus))
2309 }
2310
2311 /// Simultaneously waits for the child to exit and collect all remaining
2312 /// output on the stdout/stderr handles, returning an `Output`
2313 /// instance.
2314 ///
2315 /// The stdin handle to the child process, if any, will be closed
2316 /// before waiting. This helps avoid deadlock: it ensures that the
2317 /// child does not block waiting for input from the parent, while
2318 /// the parent waits for the child to exit.
2319 ///
2320 /// By default, stdin, stdout and stderr are inherited from the parent.
2321 /// In order to capture the output into this `Result<Output>` it is
2322 /// necessary to create new pipes between parent and child. Use
2323 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
2324 ///
2325 /// # Examples
2326 ///
2327 /// ```should_panic
2328 /// use std::process::{Command, Stdio};
2329 ///
2330 /// let child = Command::new("/bin/cat")
2331 /// .arg("file.txt")
2332 /// .stdout(Stdio::piped())
2333 /// .spawn()
2334 /// .expect("failed to execute child");
2335 ///
2336 /// let output = child
2337 /// .wait_with_output()
2338 /// .expect("failed to wait on child");
2339 ///
2340 /// assert!(output.status.success());
2341 /// ```
2342 ///
2343 #[stable(feature = "process", since = "1.0.0")]
2344 pub fn wait_with_output(mut self) -> io::Result<Output> {
2345 drop(self.stdin.take());
2346
2347 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
2348 match (self.stdout.take(), self.stderr.take()) {
2349 (None, None) => {}
2350 (Some(mut out), None) => {
2351 let res = out.read_to_end(&mut stdout);
2352 res.unwrap();
2353 }
2354 (None, Some(mut err)) => {
2355 let res = err.read_to_end(&mut stderr);
2356 res.unwrap();
2357 }
2358 (Some(out), Some(err)) => {
2359 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
2360 res.unwrap();
2361 }
2362 }
2363
2364 let status = self.wait()?;
2365 Ok(Output { status, stdout, stderr })
2366 }
2367}
2368
2369/// Terminates the current process with the specified exit code.
2370///
2371/// This function will never return and will immediately terminate the current
2372/// process. The exit code is passed through to the underlying OS and will be
2373/// available for consumption by another process.
2374///
2375/// Note that because this function never returns, and that it terminates the
2376/// process, no destructors on the current stack or any other thread's stack
2377/// will be run. If a clean shutdown is needed it is recommended to only call
2378/// this function at a known point where there are no more destructors left
2379/// to run; or, preferably, simply return a type implementing [`Termination`]
2380/// (such as [`ExitCode`] or `Result`) from the `main` function and avoid this
2381/// function altogether:
2382///
2383/// ```
2384/// # use std::io::Error as MyError;
2385/// fn main() -> Result<(), MyError> {
2386/// // ...
2387/// Ok(())
2388/// }
2389/// ```
2390///
2391/// In its current implementation, this function will execute exit handlers registered with `atexit`
2392/// as well as other platform-specific exit handlers (e.g. `fini` sections of ELF shared objects).
2393/// This means that Rust requires that all exit handlers are safe to execute at any time. In
2394/// particular, if an exit handler cleans up some state that might be concurrently accessed by other
2395/// threads, it is required that the exit handler performs suitable synchronization with those
2396/// threads. (The alternative to this requirement would be to not run exit handlers at all, which is
2397/// considered undesirable. Note that returning from `main` also calls `exit`, so making `exit` an
2398/// unsafe operation is not an option.)
2399///
2400/// ## Platform-specific behavior
2401///
2402/// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
2403/// will be visible to a parent process inspecting the exit code. On most
2404/// Unix-like platforms, only the eight least-significant bits are considered.
2405///
2406/// For example, the exit code for this example will be `0` on Linux, but `256`
2407/// on Windows:
2408///
2409/// ```no_run
2410/// use std::process;
2411///
2412/// process::exit(0x0100);
2413/// ```
2414///
2415/// ### Safe interop with C code
2416///
2417/// On Unix, this function is currently implemented using the `exit` C function [`exit`][C-exit]. As
2418/// of C23, the C standard does not permit multiple threads to call `exit` concurrently. Rust
2419/// mitigates this with a lock, but if C code calls `exit`, that can still cause undefined behavior.
2420/// Note that returning from `main` is equivalent to calling `exit`.
2421///
2422/// Therefore, it is undefined behavior to have two concurrent threads perform the following
2423/// without synchronization:
2424/// - One thread calls Rust's `exit` function or returns from Rust's `main` function
2425/// - Another thread calls the C function `exit` or `quick_exit`, or returns from C's `main` function
2426///
2427/// Note that if a binary contains multiple copies of the Rust runtime (e.g., when combining
2428/// multiple `cdylib` or `staticlib`), they each have their own separate lock, so from the
2429/// perspective of code running in one of the Rust runtimes, the "outside" Rust code is basically C
2430/// code, and concurrent `exit` again causes undefined behavior.
2431///
2432/// Individual C implementations might provide more guarantees than the standard and permit concurrent
2433/// calls to `exit`; consult the documentation of your C implementation for details.
2434///
2435/// For some of the on-going discussion to make `exit` thread-safe in C, see:
2436/// - [Rust issue #126600](https://github.com/rust-lang/rust/issues/126600)
2437/// - [Austin Group Bugzilla (for POSIX)](https://austingroupbugs.net/view.php?id=1845)
2438/// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=31997)
2439///
2440/// [C-exit]: https://en.cppreference.com/w/c/program/exit
2441#[stable(feature = "rust1", since = "1.0.0")]
2442#[cfg_attr(not(test), rustc_diagnostic_item = "process_exit")]
2443pub fn exit(code: i32) -> ! {
2444 crate::rt::cleanup();
2445 crate::sys::os::exit(code)
2446}
2447
2448/// Terminates the process in an abnormal fashion.
2449///
2450/// The function will never return and will immediately terminate the current
2451/// process in a platform specific "abnormal" manner. As a consequence,
2452/// no destructors on the current stack or any other thread's stack
2453/// will be run, Rust IO buffers (eg, from `BufWriter`) will not be flushed,
2454/// and C stdio buffers will (on most platforms) not be flushed.
2455///
2456/// This is in contrast to the default behavior of [`panic!`] which unwinds
2457/// the current thread's stack and calls all destructors.
2458/// When `panic="abort"` is set, either as an argument to `rustc` or in a
2459/// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
2460/// [`panic!`] will still call the [panic hook] while `abort` will not.
2461///
2462/// If a clean shutdown is needed it is recommended to only call
2463/// this function at a known point where there are no more destructors left
2464/// to run.
2465///
2466/// The process's termination will be similar to that from the C `abort()`
2467/// function. On Unix, the process will terminate with signal `SIGABRT`, which
2468/// typically means that the shell prints "Aborted".
2469///
2470/// # Examples
2471///
2472/// ```no_run
2473/// use std::process;
2474///
2475/// fn main() {
2476/// println!("aborting");
2477///
2478/// process::abort();
2479///
2480/// // execution never gets here
2481/// }
2482/// ```
2483///
2484/// The `abort` function terminates the process, so the destructor will not
2485/// get run on the example below:
2486///
2487/// ```no_run
2488/// use std::process;
2489///
2490/// struct HasDrop;
2491///
2492/// impl Drop for HasDrop {
2493/// fn drop(&mut self) {
2494/// println!("This will never be printed!");
2495/// }
2496/// }
2497///
2498/// fn main() {
2499/// let _x = HasDrop;
2500/// process::abort();
2501/// // the destructor implemented for HasDrop will never get run
2502/// }
2503/// ```
2504///
2505/// [panic hook]: crate::panic::set_hook
2506#[stable(feature = "process_abort", since = "1.17.0")]
2507#[cold]
2508#[cfg_attr(not(test), rustc_diagnostic_item = "process_abort")]
2509#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2510pub fn abort() -> ! {
2511 crate::sys::abort_internal();
2512}
2513
2514/// Returns the OS-assigned process identifier associated with this process.
2515///
2516/// # Examples
2517///
2518/// ```no_run
2519/// use std::process;
2520///
2521/// println!("My pid is {}", process::id());
2522/// ```
2523#[must_use]
2524#[stable(feature = "getpid", since = "1.26.0")]
2525pub fn id() -> u32 {
2526 crate::sys::os::getpid()
2527}
2528
2529/// A trait for implementing arbitrary return types in the `main` function.
2530///
2531/// The C-main function only supports returning integers.
2532/// So, every type implementing the `Termination` trait has to be converted
2533/// to an integer.
2534///
2535/// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2536/// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2537///
2538/// Because different runtimes have different specifications on the return value
2539/// of the `main` function, this trait is likely to be available only on
2540/// standard library's runtime for convenience. Other runtimes are not required
2541/// to provide similar functionality.
2542#[cfg_attr(not(any(test, doctest)), lang = "termination")]
2543#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2544#[rustc_on_unimplemented(on(
2545 cause = "MainFunctionType",
2546 message = "`main` has invalid return type `{Self}`",
2547 label = "`main` can only return types that implement `{This}`"
2548))]
2549pub trait Termination {
2550 /// Is called to get the representation of the value as status code.
2551 /// This status code is returned to the operating system.
2552 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2553 fn report(self) -> ExitCode;
2554}
2555
2556#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2557impl Termination for () {
2558 #[inline]
2559 fn report(self) -> ExitCode {
2560 ExitCode::SUCCESS
2561 }
2562}
2563
2564#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2565impl Termination for ! {
2566 fn report(self) -> ExitCode {
2567 self
2568 }
2569}
2570
2571#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2572impl Termination for Infallible {
2573 fn report(self) -> ExitCode {
2574 match self {}
2575 }
2576}
2577
2578#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2579impl Termination for ExitCode {
2580 #[inline]
2581 fn report(self) -> ExitCode {
2582 self
2583 }
2584}
2585
2586#[stable(feature = "termination_trait_lib", since = "1.61.0")]
2587impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
2588 fn report(self) -> ExitCode {
2589 match self {
2590 Ok(val) => val.report(),
2591 Err(err) => {
2592 io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));
2593 ExitCode::FAILURE
2594 }
2595 }
2596 }
2597}