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