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