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