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