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