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