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