]> git.lizzy.rs Git - rust.git/blob - library/std/src/process.rs
Merge from rustc
[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     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1042         self.inner.fmt(f)
1043     }
1044 }
1045
1046 impl AsInner<imp::Command> for Command {
1047     fn as_inner(&self) -> &imp::Command {
1048         &self.inner
1049     }
1050 }
1051
1052 impl AsInnerMut<imp::Command> for Command {
1053     fn as_inner_mut(&mut self) -> &mut imp::Command {
1054         &mut self.inner
1055     }
1056 }
1057
1058 /// An iterator over the command arguments.
1059 ///
1060 /// This struct is created by [`Command::get_args`]. See its documentation for
1061 /// more.
1062 #[must_use = "iterators are lazy and do nothing unless consumed"]
1063 #[stable(feature = "command_access", since = "1.57.0")]
1064 #[derive(Debug)]
1065 pub struct CommandArgs<'a> {
1066     inner: imp::CommandArgs<'a>,
1067 }
1068
1069 #[stable(feature = "command_access", since = "1.57.0")]
1070 impl<'a> Iterator for CommandArgs<'a> {
1071     type Item = &'a OsStr;
1072     fn next(&mut self) -> Option<&'a OsStr> {
1073         self.inner.next()
1074     }
1075     fn size_hint(&self) -> (usize, Option<usize>) {
1076         self.inner.size_hint()
1077     }
1078 }
1079
1080 #[stable(feature = "command_access", since = "1.57.0")]
1081 impl<'a> ExactSizeIterator for CommandArgs<'a> {
1082     fn len(&self) -> usize {
1083         self.inner.len()
1084     }
1085     fn is_empty(&self) -> bool {
1086         self.inner.is_empty()
1087     }
1088 }
1089
1090 /// The output of a finished process.
1091 ///
1092 /// This is returned in a Result by either the [`output`] method of a
1093 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1094 /// process.
1095 ///
1096 /// [`output`]: Command::output
1097 /// [`wait_with_output`]: Child::wait_with_output
1098 #[derive(PartialEq, Eq, Clone)]
1099 #[stable(feature = "process", since = "1.0.0")]
1100 pub struct Output {
1101     /// The status (exit code) of the process.
1102     #[stable(feature = "process", since = "1.0.0")]
1103     pub status: ExitStatus,
1104     /// The data that the process wrote to stdout.
1105     #[stable(feature = "process", since = "1.0.0")]
1106     pub stdout: Vec<u8>,
1107     /// The data that the process wrote to stderr.
1108     #[stable(feature = "process", since = "1.0.0")]
1109     pub stderr: Vec<u8>,
1110 }
1111
1112 // If either stderr or stdout are valid utf8 strings it prints the valid
1113 // strings, otherwise it prints the byte sequence instead
1114 #[stable(feature = "process_output_debug", since = "1.7.0")]
1115 impl fmt::Debug for Output {
1116     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1117         let stdout_utf8 = str::from_utf8(&self.stdout);
1118         let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1119             Ok(ref str) => str,
1120             Err(_) => &self.stdout,
1121         };
1122
1123         let stderr_utf8 = str::from_utf8(&self.stderr);
1124         let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1125             Ok(ref str) => str,
1126             Err(_) => &self.stderr,
1127         };
1128
1129         fmt.debug_struct("Output")
1130             .field("status", &self.status)
1131             .field("stdout", stdout_debug)
1132             .field("stderr", stderr_debug)
1133             .finish()
1134     }
1135 }
1136
1137 /// Describes what to do with a standard I/O stream for a child process when
1138 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1139 ///
1140 /// [`stdin`]: Command::stdin
1141 /// [`stdout`]: Command::stdout
1142 /// [`stderr`]: Command::stderr
1143 #[stable(feature = "process", since = "1.0.0")]
1144 pub struct Stdio(imp::Stdio);
1145
1146 impl Stdio {
1147     /// A new pipe should be arranged to connect the parent and child processes.
1148     ///
1149     /// # Examples
1150     ///
1151     /// With stdout:
1152     ///
1153     /// ```no_run
1154     /// use std::process::{Command, Stdio};
1155     ///
1156     /// let output = Command::new("echo")
1157     ///     .arg("Hello, world!")
1158     ///     .stdout(Stdio::piped())
1159     ///     .output()
1160     ///     .expect("Failed to execute command");
1161     ///
1162     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1163     /// // Nothing echoed to console
1164     /// ```
1165     ///
1166     /// With stdin:
1167     ///
1168     /// ```no_run
1169     /// use std::io::Write;
1170     /// use std::process::{Command, Stdio};
1171     ///
1172     /// let mut child = Command::new("rev")
1173     ///     .stdin(Stdio::piped())
1174     ///     .stdout(Stdio::piped())
1175     ///     .spawn()
1176     ///     .expect("Failed to spawn child process");
1177     ///
1178     /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1179     /// std::thread::spawn(move || {
1180     ///     stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1181     /// });
1182     ///
1183     /// let output = child.wait_with_output().expect("Failed to read stdout");
1184     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1185     /// ```
1186     ///
1187     /// Writing more than a pipe buffer's worth of input to stdin without also reading
1188     /// stdout and stderr at the same time may cause a deadlock.
1189     /// This is an issue when running any program that doesn't guarantee that it reads
1190     /// its entire stdin before writing more than a pipe buffer's worth of output.
1191     /// The size of a pipe buffer varies on different targets.
1192     ///
1193     #[must_use]
1194     #[stable(feature = "process", since = "1.0.0")]
1195     pub fn piped() -> Stdio {
1196         Stdio(imp::Stdio::MakePipe)
1197     }
1198
1199     /// The child inherits from the corresponding parent descriptor.
1200     ///
1201     /// # Examples
1202     ///
1203     /// With stdout:
1204     ///
1205     /// ```no_run
1206     /// use std::process::{Command, Stdio};
1207     ///
1208     /// let output = Command::new("echo")
1209     ///     .arg("Hello, world!")
1210     ///     .stdout(Stdio::inherit())
1211     ///     .output()
1212     ///     .expect("Failed to execute command");
1213     ///
1214     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1215     /// // "Hello, world!" echoed to console
1216     /// ```
1217     ///
1218     /// With stdin:
1219     ///
1220     /// ```no_run
1221     /// use std::process::{Command, Stdio};
1222     /// use std::io::{self, Write};
1223     ///
1224     /// let output = Command::new("rev")
1225     ///     .stdin(Stdio::inherit())
1226     ///     .stdout(Stdio::piped())
1227     ///     .output()
1228     ///     .expect("Failed to execute command");
1229     ///
1230     /// print!("You piped in the reverse of: ");
1231     /// io::stdout().write_all(&output.stdout).unwrap();
1232     /// ```
1233     #[must_use]
1234     #[stable(feature = "process", since = "1.0.0")]
1235     pub fn inherit() -> Stdio {
1236         Stdio(imp::Stdio::Inherit)
1237     }
1238
1239     /// This stream will be ignored. This is the equivalent of attaching the
1240     /// stream to `/dev/null`.
1241     ///
1242     /// # Examples
1243     ///
1244     /// With stdout:
1245     ///
1246     /// ```no_run
1247     /// use std::process::{Command, Stdio};
1248     ///
1249     /// let output = Command::new("echo")
1250     ///     .arg("Hello, world!")
1251     ///     .stdout(Stdio::null())
1252     ///     .output()
1253     ///     .expect("Failed to execute command");
1254     ///
1255     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1256     /// // Nothing echoed to console
1257     /// ```
1258     ///
1259     /// With stdin:
1260     ///
1261     /// ```no_run
1262     /// use std::process::{Command, Stdio};
1263     ///
1264     /// let output = Command::new("rev")
1265     ///     .stdin(Stdio::null())
1266     ///     .stdout(Stdio::piped())
1267     ///     .output()
1268     ///     .expect("Failed to execute command");
1269     ///
1270     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1271     /// // Ignores any piped-in input
1272     /// ```
1273     #[must_use]
1274     #[stable(feature = "process", since = "1.0.0")]
1275     pub fn null() -> Stdio {
1276         Stdio(imp::Stdio::Null)
1277     }
1278
1279     /// Returns `true` if this requires [`Command`] to create a new pipe.
1280     ///
1281     /// # Example
1282     ///
1283     /// ```
1284     /// #![feature(stdio_makes_pipe)]
1285     /// use std::process::Stdio;
1286     ///
1287     /// let io = Stdio::piped();
1288     /// assert_eq!(io.makes_pipe(), true);
1289     /// ```
1290     #[unstable(feature = "stdio_makes_pipe", issue = "98288")]
1291     pub fn makes_pipe(&self) -> bool {
1292         matches!(self.0, imp::Stdio::MakePipe)
1293     }
1294 }
1295
1296 impl FromInner<imp::Stdio> for Stdio {
1297     fn from_inner(inner: imp::Stdio) -> Stdio {
1298         Stdio(inner)
1299     }
1300 }
1301
1302 #[stable(feature = "std_debug", since = "1.16.0")]
1303 impl fmt::Debug for Stdio {
1304     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1305         f.debug_struct("Stdio").finish_non_exhaustive()
1306     }
1307 }
1308
1309 #[stable(feature = "stdio_from", since = "1.20.0")]
1310 impl From<ChildStdin> for Stdio {
1311     /// Converts a [`ChildStdin`] into a [`Stdio`].
1312     ///
1313     /// # Examples
1314     ///
1315     /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1316     ///
1317     /// ```rust,no_run
1318     /// use std::process::{Command, Stdio};
1319     ///
1320     /// let reverse = Command::new("rev")
1321     ///     .stdin(Stdio::piped())
1322     ///     .spawn()
1323     ///     .expect("failed reverse command");
1324     ///
1325     /// let _echo = Command::new("echo")
1326     ///     .arg("Hello, world!")
1327     ///     .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1328     ///     .output()
1329     ///     .expect("failed echo command");
1330     ///
1331     /// // "!dlrow ,olleH" echoed to console
1332     /// ```
1333     fn from(child: ChildStdin) -> Stdio {
1334         Stdio::from_inner(child.into_inner().into())
1335     }
1336 }
1337
1338 #[stable(feature = "stdio_from", since = "1.20.0")]
1339 impl From<ChildStdout> for Stdio {
1340     /// Converts a [`ChildStdout`] into a [`Stdio`].
1341     ///
1342     /// # Examples
1343     ///
1344     /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1345     ///
1346     /// ```rust,no_run
1347     /// use std::process::{Command, Stdio};
1348     ///
1349     /// let hello = Command::new("echo")
1350     ///     .arg("Hello, world!")
1351     ///     .stdout(Stdio::piped())
1352     ///     .spawn()
1353     ///     .expect("failed echo command");
1354     ///
1355     /// let reverse = Command::new("rev")
1356     ///     .stdin(hello.stdout.unwrap())  // Converted into a Stdio here
1357     ///     .output()
1358     ///     .expect("failed reverse command");
1359     ///
1360     /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1361     /// ```
1362     fn from(child: ChildStdout) -> Stdio {
1363         Stdio::from_inner(child.into_inner().into())
1364     }
1365 }
1366
1367 #[stable(feature = "stdio_from", since = "1.20.0")]
1368 impl From<ChildStderr> for Stdio {
1369     /// Converts a [`ChildStderr`] into a [`Stdio`].
1370     ///
1371     /// # Examples
1372     ///
1373     /// ```rust,no_run
1374     /// use std::process::{Command, Stdio};
1375     ///
1376     /// let reverse = Command::new("rev")
1377     ///     .arg("non_existing_file.txt")
1378     ///     .stderr(Stdio::piped())
1379     ///     .spawn()
1380     ///     .expect("failed reverse command");
1381     ///
1382     /// let cat = Command::new("cat")
1383     ///     .arg("-")
1384     ///     .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1385     ///     .output()
1386     ///     .expect("failed echo command");
1387     ///
1388     /// assert_eq!(
1389     ///     String::from_utf8_lossy(&cat.stdout),
1390     ///     "rev: cannot open non_existing_file.txt: No such file or directory\n"
1391     /// );
1392     /// ```
1393     fn from(child: ChildStderr) -> Stdio {
1394         Stdio::from_inner(child.into_inner().into())
1395     }
1396 }
1397
1398 #[stable(feature = "stdio_from", since = "1.20.0")]
1399 impl From<fs::File> for Stdio {
1400     /// Converts a [`File`](fs::File) into a [`Stdio`].
1401     ///
1402     /// # Examples
1403     ///
1404     /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1405     ///
1406     /// ```rust,no_run
1407     /// use std::fs::File;
1408     /// use std::process::Command;
1409     ///
1410     /// // With the `foo.txt` file containing `Hello, world!"
1411     /// let file = File::open("foo.txt").unwrap();
1412     ///
1413     /// let reverse = Command::new("rev")
1414     ///     .stdin(file)  // Implicit File conversion into a Stdio
1415     ///     .output()
1416     ///     .expect("failed reverse command");
1417     ///
1418     /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1419     /// ```
1420     fn from(file: fs::File) -> Stdio {
1421         Stdio::from_inner(file.into_inner().into())
1422     }
1423 }
1424
1425 /// Describes the result of a process after it has terminated.
1426 ///
1427 /// This `struct` is used to represent the exit status or other termination of a child process.
1428 /// Child processes are created via the [`Command`] struct and their exit
1429 /// status is exposed through the [`status`] method, or the [`wait`] method
1430 /// of a [`Child`] process.
1431 ///
1432 /// An `ExitStatus` represents every possible disposition of a process.  On Unix this
1433 /// is the **wait status**.  It is *not* simply an *exit status* (a value passed to `exit`).
1434 ///
1435 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1436 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1437 ///
1438 /// # Differences from `ExitCode`
1439 ///
1440 /// [`ExitCode`] is intended for terminating the currently running process, via
1441 /// the `Termination` trait, in contrast to `ExitStatus`, which represents the
1442 /// termination of a child process. These APIs are separate due to platform
1443 /// compatibility differences and their expected usage; it is not generally
1444 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1445 /// process after the fact.
1446 ///
1447 /// [`status`]: Command::status
1448 /// [`wait`]: Child::wait
1449 //
1450 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1451 // vs `_exit`.  Naming of Unix system calls is not standardised across Unices, so terminology is a
1452 // matter of convention and tradition.  For clarity we usually speak of `exit`, even when we might
1453 // mean an underlying system call such as `_exit`.
1454 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1455 #[stable(feature = "process", since = "1.0.0")]
1456 pub struct ExitStatus(imp::ExitStatus);
1457
1458 /// Allows extension traits within `std`.
1459 #[unstable(feature = "sealed", issue = "none")]
1460 impl crate::sealed::Sealed for ExitStatus {}
1461
1462 impl ExitStatus {
1463     /// Was termination successful?  Returns a `Result`.
1464     ///
1465     /// # Examples
1466     ///
1467     /// ```
1468     /// #![feature(exit_status_error)]
1469     /// # if cfg!(unix) {
1470     /// use std::process::Command;
1471     ///
1472     /// let status = Command::new("ls")
1473     ///                      .arg("/dev/nonexistent")
1474     ///                      .status()
1475     ///                      .expect("ls could not be executed");
1476     ///
1477     /// println!("ls: {status}");
1478     /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1479     /// # } // cfg!(unix)
1480     /// ```
1481     #[unstable(feature = "exit_status_error", issue = "84908")]
1482     pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1483         self.0.exit_ok().map_err(ExitStatusError)
1484     }
1485
1486     /// Was termination successful? Signal termination is not considered a
1487     /// success, and success is defined as a zero exit status.
1488     ///
1489     /// # Examples
1490     ///
1491     /// ```rust,no_run
1492     /// use std::process::Command;
1493     ///
1494     /// let status = Command::new("mkdir")
1495     ///                      .arg("projects")
1496     ///                      .status()
1497     ///                      .expect("failed to execute mkdir");
1498     ///
1499     /// if status.success() {
1500     ///     println!("'projects/' directory created");
1501     /// } else {
1502     ///     println!("failed to create 'projects/' directory: {status}");
1503     /// }
1504     /// ```
1505     #[must_use]
1506     #[stable(feature = "process", since = "1.0.0")]
1507     pub fn success(&self) -> bool {
1508         self.0.exit_ok().is_ok()
1509     }
1510
1511     /// Returns the exit code of the process, if any.
1512     ///
1513     /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1514     /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1515     /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1516     /// runtime system (often, for example, 255, 254, 127 or 126).
1517     ///
1518     /// On Unix, this will return `None` if the process was terminated by a signal.
1519     /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1520     /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1521     ///
1522     /// # Examples
1523     ///
1524     /// ```no_run
1525     /// use std::process::Command;
1526     ///
1527     /// let status = Command::new("mkdir")
1528     ///                      .arg("projects")
1529     ///                      .status()
1530     ///                      .expect("failed to execute mkdir");
1531     ///
1532     /// match status.code() {
1533     ///     Some(code) => println!("Exited with status code: {code}"),
1534     ///     None       => println!("Process terminated by signal")
1535     /// }
1536     /// ```
1537     #[must_use]
1538     #[stable(feature = "process", since = "1.0.0")]
1539     pub fn code(&self) -> Option<i32> {
1540         self.0.code()
1541     }
1542 }
1543
1544 impl AsInner<imp::ExitStatus> for ExitStatus {
1545     fn as_inner(&self) -> &imp::ExitStatus {
1546         &self.0
1547     }
1548 }
1549
1550 impl FromInner<imp::ExitStatus> for ExitStatus {
1551     fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1552         ExitStatus(s)
1553     }
1554 }
1555
1556 #[stable(feature = "process", since = "1.0.0")]
1557 impl fmt::Display for ExitStatus {
1558     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1559         self.0.fmt(f)
1560     }
1561 }
1562
1563 /// Allows extension traits within `std`.
1564 #[unstable(feature = "sealed", issue = "none")]
1565 impl crate::sealed::Sealed for ExitStatusError {}
1566
1567 /// Describes the result of a process after it has failed
1568 ///
1569 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1570 ///
1571 /// # Examples
1572 ///
1573 /// ```
1574 /// #![feature(exit_status_error)]
1575 /// # if cfg!(unix) {
1576 /// use std::process::{Command, ExitStatusError};
1577 ///
1578 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1579 ///     Command::new(cmd).status().unwrap().exit_ok()?;
1580 ///     Ok(())
1581 /// }
1582 ///
1583 /// run("true").unwrap();
1584 /// run("false").unwrap_err();
1585 /// # } // cfg!(unix)
1586 /// ```
1587 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1588 #[unstable(feature = "exit_status_error", issue = "84908")]
1589 // The definition of imp::ExitStatusError should ideally be such that
1590 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1591 pub struct ExitStatusError(imp::ExitStatusError);
1592
1593 #[unstable(feature = "exit_status_error", issue = "84908")]
1594 impl ExitStatusError {
1595     /// Reports the exit code, if applicable, from an `ExitStatusError`.
1596     ///
1597     /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1598     /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
1599     /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1600     /// runtime system (often, for example, 255, 254, 127 or 126).
1601     ///
1602     /// On Unix, this will return `None` if the process was terminated by a signal.  If you want to
1603     /// handle such situations specially, consider using methods from
1604     /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1605     ///
1606     /// If the process finished by calling `exit` with a nonzero value, this will return
1607     /// that exit status.
1608     ///
1609     /// If the error was something else, it will return `None`.
1610     ///
1611     /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1612     /// `ExitStatusError`.  So the return value from `ExitStatusError::code()` is always nonzero.
1613     ///
1614     /// # Examples
1615     ///
1616     /// ```
1617     /// #![feature(exit_status_error)]
1618     /// # #[cfg(unix)] {
1619     /// use std::process::Command;
1620     ///
1621     /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1622     /// assert_eq!(bad.code(), Some(1));
1623     /// # } // #[cfg(unix)]
1624     /// ```
1625     #[must_use]
1626     pub fn code(&self) -> Option<i32> {
1627         self.code_nonzero().map(Into::into)
1628     }
1629
1630     /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1631     ///
1632     /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1633     ///
1634     /// Plain `code`, returning a plain integer, is provided because it is often more convenient.
1635     /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1636     /// a type-level guarantee of nonzeroness.
1637     ///
1638     /// # Examples
1639     ///
1640     /// ```
1641     /// #![feature(exit_status_error)]
1642     /// # if cfg!(unix) {
1643     /// use std::num::NonZeroI32;
1644     /// use std::process::Command;
1645     ///
1646     /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1647     /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1648     /// # } // cfg!(unix)
1649     /// ```
1650     #[must_use]
1651     pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1652         self.0.code()
1653     }
1654
1655     /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1656     #[must_use]
1657     pub fn into_status(&self) -> ExitStatus {
1658         ExitStatus(self.0.into())
1659     }
1660 }
1661
1662 #[unstable(feature = "exit_status_error", issue = "84908")]
1663 impl Into<ExitStatus> for ExitStatusError {
1664     fn into(self) -> ExitStatus {
1665         ExitStatus(self.0.into())
1666     }
1667 }
1668
1669 #[unstable(feature = "exit_status_error", issue = "84908")]
1670 impl fmt::Display for ExitStatusError {
1671     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1672         write!(f, "process exited unsuccessfully: {}", self.into_status())
1673     }
1674 }
1675
1676 #[unstable(feature = "exit_status_error", issue = "84908")]
1677 impl crate::error::Error for ExitStatusError {}
1678
1679 /// This type represents the status code the current process can return
1680 /// to its parent under normal termination.
1681 ///
1682 /// `ExitCode` is intended to be consumed only by the standard library (via
1683 /// [`Termination::report()`]), and intentionally does not provide accessors like
1684 /// `PartialEq`, `Eq`, or `Hash`. Instead the standard library provides the
1685 /// canonical `SUCCESS` and `FAILURE` exit codes as well as `From<u8> for
1686 /// ExitCode` for constructing other arbitrary exit codes.
1687 ///
1688 /// # Portability
1689 ///
1690 /// Numeric values used in this type don't have portable meanings, and
1691 /// different platforms may mask different amounts of them.
1692 ///
1693 /// For the platform's canonical successful and unsuccessful codes, see
1694 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1695 ///
1696 /// [`SUCCESS`]: ExitCode::SUCCESS
1697 /// [`FAILURE`]: ExitCode::FAILURE
1698 ///
1699 /// # Differences from `ExitStatus`
1700 ///
1701 /// `ExitCode` is intended for terminating the currently running process, via
1702 /// the `Termination` trait, in contrast to [`ExitStatus`], which represents the
1703 /// termination of a child process. These APIs are separate due to platform
1704 /// compatibility differences and their expected usage; it is not generally
1705 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1706 /// process after the fact.
1707 ///
1708 /// # Examples
1709 ///
1710 /// `ExitCode` can be returned from the `main` function of a crate, as it implements
1711 /// [`Termination`]:
1712 ///
1713 /// ```
1714 /// use std::process::ExitCode;
1715 /// # fn check_foo() -> bool { true }
1716 ///
1717 /// fn main() -> ExitCode {
1718 ///     if !check_foo() {
1719 ///         return ExitCode::from(42);
1720 ///     }
1721 ///
1722 ///     ExitCode::SUCCESS
1723 /// }
1724 /// ```
1725 #[derive(Clone, Copy, Debug)]
1726 #[stable(feature = "process_exitcode", since = "1.61.0")]
1727 pub struct ExitCode(imp::ExitCode);
1728
1729 /// Allows extension traits within `std`.
1730 #[unstable(feature = "sealed", issue = "none")]
1731 impl crate::sealed::Sealed for ExitCode {}
1732
1733 #[stable(feature = "process_exitcode", since = "1.61.0")]
1734 impl ExitCode {
1735     /// The canonical `ExitCode` for successful termination on this platform.
1736     ///
1737     /// Note that a `()`-returning `main` implicitly results in a successful
1738     /// termination, so there's no need to return this from `main` unless
1739     /// you're also returning other possible codes.
1740     #[stable(feature = "process_exitcode", since = "1.61.0")]
1741     pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1742
1743     /// The canonical `ExitCode` for unsuccessful termination on this platform.
1744     ///
1745     /// If you're only returning this and `SUCCESS` from `main`, consider
1746     /// instead returning `Err(_)` and `Ok(())` respectively, which will
1747     /// return the same codes (but will also `eprintln!` the error).
1748     #[stable(feature = "process_exitcode", since = "1.61.0")]
1749     pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1750
1751     /// Exit the current process with the given `ExitCode`.
1752     ///
1753     /// Note that this has the same caveats as [`process::exit()`][exit], namely that this function
1754     /// terminates the process immediately, so no destructors on the current stack or any other
1755     /// thread's stack will be run. If a clean shutdown is needed, it is recommended to simply
1756     /// return this ExitCode from the `main` function, as demonstrated in the [type
1757     /// documentation](#examples).
1758     ///
1759     /// # Differences from `process::exit()`
1760     ///
1761     /// `process::exit()` accepts any `i32` value as the exit code for the process; however, there
1762     /// are platforms that only use a subset of that value (see [`process::exit` platform-specific
1763     /// behavior][exit#platform-specific-behavior]). `ExitCode` exists because of this; only
1764     /// `ExitCode`s that are supported by a majority of our platforms can be created, so those
1765     /// problems don't exist (as much) with this method.
1766     ///
1767     /// # Examples
1768     ///
1769     /// ```
1770     /// #![feature(exitcode_exit_method)]
1771     /// # use std::process::ExitCode;
1772     /// # use std::fmt;
1773     /// # enum UhOhError { GenericProblem, Specific, WithCode { exit_code: ExitCode, _x: () } }
1774     /// # impl fmt::Display for UhOhError {
1775     /// #     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() }
1776     /// # }
1777     /// // there's no way to gracefully recover from an UhOhError, so we just
1778     /// // print a message and exit
1779     /// fn handle_unrecoverable_error(err: UhOhError) -> ! {
1780     ///     eprintln!("UH OH! {err}");
1781     ///     let code = match err {
1782     ///         UhOhError::GenericProblem => ExitCode::FAILURE,
1783     ///         UhOhError::Specific => ExitCode::from(3),
1784     ///         UhOhError::WithCode { exit_code, .. } => exit_code,
1785     ///     };
1786     ///     code.exit_process()
1787     /// }
1788     /// ```
1789     #[unstable(feature = "exitcode_exit_method", issue = "97100")]
1790     pub fn exit_process(self) -> ! {
1791         exit(self.to_i32())
1792     }
1793 }
1794
1795 impl ExitCode {
1796     // This is private/perma-unstable because ExitCode is opaque; we don't know that i32 will serve
1797     // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
1798     // likely want to isolate users anything that could restrict the platform specific
1799     // representation of an ExitCode
1800     //
1801     // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
1802     /// Convert an `ExitCode` into an i32
1803     #[unstable(
1804         feature = "process_exitcode_internals",
1805         reason = "exposed only for libstd",
1806         issue = "none"
1807     )]
1808     #[inline]
1809     #[doc(hidden)]
1810     pub fn to_i32(self) -> i32 {
1811         self.0.as_i32()
1812     }
1813 }
1814
1815 #[stable(feature = "process_exitcode", since = "1.61.0")]
1816 impl From<u8> for ExitCode {
1817     /// Construct an `ExitCode` from an arbitrary u8 value.
1818     fn from(code: u8) -> Self {
1819         ExitCode(imp::ExitCode::from(code))
1820     }
1821 }
1822
1823 impl AsInner<imp::ExitCode> for ExitCode {
1824     fn as_inner(&self) -> &imp::ExitCode {
1825         &self.0
1826     }
1827 }
1828
1829 impl FromInner<imp::ExitCode> for ExitCode {
1830     fn from_inner(s: imp::ExitCode) -> ExitCode {
1831         ExitCode(s)
1832     }
1833 }
1834
1835 impl Child {
1836     /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
1837     /// error is returned.
1838     ///
1839     /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1840     ///
1841     /// This is equivalent to sending a SIGKILL on Unix platforms.
1842     ///
1843     /// # Examples
1844     ///
1845     /// Basic usage:
1846     ///
1847     /// ```no_run
1848     /// use std::process::Command;
1849     ///
1850     /// let mut command = Command::new("yes");
1851     /// if let Ok(mut child) = command.spawn() {
1852     ///     child.kill().expect("command wasn't running");
1853     /// } else {
1854     ///     println!("yes command didn't start");
1855     /// }
1856     /// ```
1857     ///
1858     /// [`ErrorKind`]: io::ErrorKind
1859     /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1860     #[stable(feature = "process", since = "1.0.0")]
1861     pub fn kill(&mut self) -> io::Result<()> {
1862         self.handle.kill()
1863     }
1864
1865     /// Returns the OS-assigned process identifier associated with this child.
1866     ///
1867     /// # Examples
1868     ///
1869     /// Basic usage:
1870     ///
1871     /// ```no_run
1872     /// use std::process::Command;
1873     ///
1874     /// let mut command = Command::new("ls");
1875     /// if let Ok(child) = command.spawn() {
1876     ///     println!("Child's ID is {}", child.id());
1877     /// } else {
1878     ///     println!("ls command didn't start");
1879     /// }
1880     /// ```
1881     #[must_use]
1882     #[stable(feature = "process_id", since = "1.3.0")]
1883     pub fn id(&self) -> u32 {
1884         self.handle.id()
1885     }
1886
1887     /// Waits for the child to exit completely, returning the status that it
1888     /// exited with. This function will continue to have the same return value
1889     /// after it has been called at least once.
1890     ///
1891     /// The stdin handle to the child process, if any, will be closed
1892     /// before waiting. This helps avoid deadlock: it ensures that the
1893     /// child does not block waiting for input from the parent, while
1894     /// the parent waits for the child to exit.
1895     ///
1896     /// # Examples
1897     ///
1898     /// Basic usage:
1899     ///
1900     /// ```no_run
1901     /// use std::process::Command;
1902     ///
1903     /// let mut command = Command::new("ls");
1904     /// if let Ok(mut child) = command.spawn() {
1905     ///     child.wait().expect("command wasn't running");
1906     ///     println!("Child has finished its execution!");
1907     /// } else {
1908     ///     println!("ls command didn't start");
1909     /// }
1910     /// ```
1911     #[stable(feature = "process", since = "1.0.0")]
1912     pub fn wait(&mut self) -> io::Result<ExitStatus> {
1913         drop(self.stdin.take());
1914         self.handle.wait().map(ExitStatus)
1915     }
1916
1917     /// Attempts to collect the exit status of the child if it has already
1918     /// exited.
1919     ///
1920     /// This function will not block the calling thread and will only
1921     /// check to see if the child process has exited or not. If the child has
1922     /// exited then on Unix the process ID is reaped. This function is
1923     /// guaranteed to repeatedly return a successful exit status so long as the
1924     /// child has already exited.
1925     ///
1926     /// If the child has exited, then `Ok(Some(status))` is returned. If the
1927     /// exit status is not available at this time then `Ok(None)` is returned.
1928     /// If an error occurs, then that error is returned.
1929     ///
1930     /// Note that unlike `wait`, this function will not attempt to drop stdin.
1931     ///
1932     /// # Examples
1933     ///
1934     /// Basic usage:
1935     ///
1936     /// ```no_run
1937     /// use std::process::Command;
1938     ///
1939     /// let mut child = Command::new("ls").spawn().unwrap();
1940     ///
1941     /// match child.try_wait() {
1942     ///     Ok(Some(status)) => println!("exited with: {status}"),
1943     ///     Ok(None) => {
1944     ///         println!("status not ready yet, let's really wait");
1945     ///         let res = child.wait();
1946     ///         println!("result: {res:?}");
1947     ///     }
1948     ///     Err(e) => println!("error attempting to wait: {e}"),
1949     /// }
1950     /// ```
1951     #[stable(feature = "process_try_wait", since = "1.18.0")]
1952     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1953         Ok(self.handle.try_wait()?.map(ExitStatus))
1954     }
1955
1956     /// Simultaneously waits for the child to exit and collect all remaining
1957     /// output on the stdout/stderr handles, returning an `Output`
1958     /// instance.
1959     ///
1960     /// The stdin handle to the child process, if any, will be closed
1961     /// before waiting. This helps avoid deadlock: it ensures that the
1962     /// child does not block waiting for input from the parent, while
1963     /// the parent waits for the child to exit.
1964     ///
1965     /// By default, stdin, stdout and stderr are inherited from the parent.
1966     /// In order to capture the output into this `Result<Output>` it is
1967     /// necessary to create new pipes between parent and child. Use
1968     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
1969     ///
1970     /// # Examples
1971     ///
1972     /// ```should_panic
1973     /// use std::process::{Command, Stdio};
1974     ///
1975     /// let child = Command::new("/bin/cat")
1976     ///     .arg("file.txt")
1977     ///     .stdout(Stdio::piped())
1978     ///     .spawn()
1979     ///     .expect("failed to execute child");
1980     ///
1981     /// let output = child
1982     ///     .wait_with_output()
1983     ///     .expect("failed to wait on child");
1984     ///
1985     /// assert!(output.status.success());
1986     /// ```
1987     ///
1988     #[stable(feature = "process", since = "1.0.0")]
1989     pub fn wait_with_output(mut self) -> io::Result<Output> {
1990         drop(self.stdin.take());
1991
1992         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
1993         match (self.stdout.take(), self.stderr.take()) {
1994             (None, None) => {}
1995             (Some(mut out), None) => {
1996                 let res = out.read_to_end(&mut stdout);
1997                 res.unwrap();
1998             }
1999             (None, Some(mut err)) => {
2000                 let res = err.read_to_end(&mut stderr);
2001                 res.unwrap();
2002             }
2003             (Some(out), Some(err)) => {
2004                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
2005                 res.unwrap();
2006             }
2007         }
2008
2009         let status = self.wait()?;
2010         Ok(Output { status, stdout, stderr })
2011     }
2012 }
2013
2014 /// Terminates the current process with the specified exit code.
2015 ///
2016 /// This function will never return and will immediately terminate the current
2017 /// process. The exit code is passed through to the underlying OS and will be
2018 /// available for consumption by another process.
2019 ///
2020 /// Note that because this function never returns, and that it terminates the
2021 /// process, no destructors on the current stack or any other thread's stack
2022 /// will be run. If a clean shutdown is needed it is recommended to only call
2023 /// this function at a known point where there are no more destructors left
2024 /// to run; or, preferably, simply return a type implementing [`Termination`]
2025 /// (such as [`ExitCode`] or `Result`) from the `main` function and avoid this
2026 /// function altogether:
2027 ///
2028 /// ```
2029 /// # use std::io::Error as MyError;
2030 /// fn main() -> Result<(), MyError> {
2031 ///     // ...
2032 ///     Ok(())
2033 /// }
2034 /// ```
2035 ///
2036 /// ## Platform-specific behavior
2037 ///
2038 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
2039 /// will be visible to a parent process inspecting the exit code. On most
2040 /// Unix-like platforms, only the eight least-significant bits are considered.
2041 ///
2042 /// For example, the exit code for this example will be `0` on Linux, but `256`
2043 /// on Windows:
2044 ///
2045 /// ```no_run
2046 /// use std::process;
2047 ///
2048 /// process::exit(0x0100);
2049 /// ```
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 pub fn exit(code: i32) -> ! {
2052     crate::rt::cleanup();
2053     crate::sys::os::exit(code)
2054 }
2055
2056 /// Terminates the process in an abnormal fashion.
2057 ///
2058 /// The function will never return and will immediately terminate the current
2059 /// process in a platform specific "abnormal" manner.
2060 ///
2061 /// Note that because this function never returns, and that it terminates the
2062 /// process, no destructors on the current stack or any other thread's stack
2063 /// will be run.
2064 ///
2065 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
2066 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
2067 ///
2068 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
2069 /// the current thread's stack and calls all destructors.
2070 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
2071 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
2072 /// [`panic!`] will still call the [panic hook] while `abort` will not.
2073 ///
2074 /// If a clean shutdown is needed it is recommended to only call
2075 /// this function at a known point where there are no more destructors left
2076 /// to run.
2077 ///
2078 /// The process's termination will be similar to that from the C `abort()`
2079 /// function.  On Unix, the process will terminate with signal `SIGABRT`, which
2080 /// typically means that the shell prints "Aborted".
2081 ///
2082 /// # Examples
2083 ///
2084 /// ```no_run
2085 /// use std::process;
2086 ///
2087 /// fn main() {
2088 ///     println!("aborting");
2089 ///
2090 ///     process::abort();
2091 ///
2092 ///     // execution never gets here
2093 /// }
2094 /// ```
2095 ///
2096 /// The `abort` function terminates the process, so the destructor will not
2097 /// get run on the example below:
2098 ///
2099 /// ```no_run
2100 /// use std::process;
2101 ///
2102 /// struct HasDrop;
2103 ///
2104 /// impl Drop for HasDrop {
2105 ///     fn drop(&mut self) {
2106 ///         println!("This will never be printed!");
2107 ///     }
2108 /// }
2109 ///
2110 /// fn main() {
2111 ///     let _x = HasDrop;
2112 ///     process::abort();
2113 ///     // the destructor implemented for HasDrop will never get run
2114 /// }
2115 /// ```
2116 ///
2117 /// [panic hook]: crate::panic::set_hook
2118 #[stable(feature = "process_abort", since = "1.17.0")]
2119 #[cold]
2120 pub fn abort() -> ! {
2121     crate::sys::abort_internal();
2122 }
2123
2124 /// Returns the OS-assigned process identifier associated with this process.
2125 ///
2126 /// # Examples
2127 ///
2128 /// Basic usage:
2129 ///
2130 /// ```no_run
2131 /// use std::process;
2132 ///
2133 /// println!("My pid is {}", process::id());
2134 /// ```
2135 ///
2136 ///
2137 #[must_use]
2138 #[stable(feature = "getpid", since = "1.26.0")]
2139 pub fn id() -> u32 {
2140     crate::sys::os::getpid()
2141 }
2142
2143 /// A trait for implementing arbitrary return types in the `main` function.
2144 ///
2145 /// The C-main function only supports returning integers.
2146 /// So, every type implementing the `Termination` trait has to be converted
2147 /// to an integer.
2148 ///
2149 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2150 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2151 ///
2152 /// Because different runtimes have different specifications on the return value
2153 /// of the `main` function, this trait is likely to be available only on
2154 /// standard library's runtime for convenience. Other runtimes are not required
2155 /// to provide similar functionality.
2156 #[cfg_attr(not(test), lang = "termination")]
2157 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2158 #[rustc_on_unimplemented(
2159     on(
2160         all(not(bootstrap), cause = "MainFunctionType"),
2161         message = "`main` has invalid return type `{Self}`",
2162         label = "`main` can only return types that implement `{Termination}`"
2163     ),
2164     on(
2165         bootstrap,
2166         message = "`main` has invalid return type `{Self}`",
2167         label = "`main` can only return types that implement `{Termination}`"
2168     )
2169 )]
2170 pub trait Termination {
2171     /// Is called to get the representation of the value as status code.
2172     /// This status code is returned to the operating system.
2173     #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2174     fn report(self) -> ExitCode;
2175 }
2176
2177 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2178 impl Termination for () {
2179     #[inline]
2180     fn report(self) -> ExitCode {
2181         ExitCode::SUCCESS
2182     }
2183 }
2184
2185 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2186 impl Termination for ! {
2187     fn report(self) -> ExitCode {
2188         self
2189     }
2190 }
2191
2192 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2193 impl Termination for Infallible {
2194     fn report(self) -> ExitCode {
2195         match self {}
2196     }
2197 }
2198
2199 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2200 impl Termination for ExitCode {
2201     #[inline]
2202     fn report(self) -> ExitCode {
2203         self
2204     }
2205 }
2206
2207 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2208 impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
2209     fn report(self) -> ExitCode {
2210         match self {
2211             Ok(val) => val.report(),
2212             Err(err) => {
2213                 io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));
2214                 ExitCode::FAILURE
2215             }
2216         }
2217     }
2218 }