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