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