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