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