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