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