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