]> git.lizzy.rs Git - rust.git/blob - src/libstd/process.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[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 //! # Examples
14 //!
15 //! Basic usage where we try to execute the `cat` shell command:
16 //!
17 //! ```should_panic
18 //! use std::process::Command;
19 //!
20 //! let mut child = Command::new("/bin/cat")
21 //!                         .arg("file.txt")
22 //!                         .spawn()
23 //!                         .expect("failed to execute child");
24 //!
25 //! let ecode = child.wait()
26 //!                  .expect("failed to wait on child");
27 //!
28 //! assert!(ecode.success());
29 //! ```
30
31 #![stable(feature = "process", since = "1.0.0")]
32
33 use io::prelude::*;
34
35 use ffi::OsStr;
36 use fmt;
37 use io;
38 use path::Path;
39 use str;
40 use sys::pipe::{read2, AnonPipe};
41 use sys::process as imp;
42 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
43
44 /// Representation of a running or exited child process.
45 ///
46 /// This structure is used to represent and manage child processes. A child
47 /// process is created via the [`Command`] struct, which configures the
48 /// spawning process and can itself be constructed using a builder-style
49 /// interface.
50 ///
51 /// # Examples
52 ///
53 /// ```should_panic
54 /// use std::process::Command;
55 ///
56 /// let mut child = Command::new("/bin/cat")
57 ///                         .arg("file.txt")
58 ///                         .spawn()
59 ///                         .expect("failed to execute child");
60 ///
61 /// let ecode = child.wait()
62 ///                  .expect("failed to wait on child");
63 ///
64 /// assert!(ecode.success());
65 /// ```
66 ///
67 /// # Note
68 ///
69 /// Take note that there is no implementation of [`Drop`] for child processes,
70 /// so if you do not ensure the `Child` has exited then it will continue to
71 /// run, even after the `Child` handle to the child process has gone out of
72 /// scope.
73 ///
74 /// Calling [`wait`][`wait`] (or other functions that wrap around it) will make
75 /// the parent process wait until the child has actually exited before
76 /// continuing.
77 ///
78 /// [`Command`]: struct.Command.html
79 /// [`Drop`]: ../../core/ops/trait.Drop.html
80 /// [`wait`]: #method.wait
81 #[stable(feature = "process", since = "1.0.0")]
82 pub struct Child {
83     handle: imp::Process,
84
85     /// The handle for writing to the child's stdin, if it has been captured
86     #[stable(feature = "process", since = "1.0.0")]
87     pub stdin: Option<ChildStdin>,
88
89     /// The handle for reading from the child's stdout, if it has been captured
90     #[stable(feature = "process", since = "1.0.0")]
91     pub stdout: Option<ChildStdout>,
92
93     /// The handle for reading from the child's stderr, if it has been captured
94     #[stable(feature = "process", since = "1.0.0")]
95     pub stderr: Option<ChildStderr>,
96 }
97
98 impl AsInner<imp::Process> for Child {
99     fn as_inner(&self) -> &imp::Process { &self.handle }
100 }
101
102 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
103     fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
104         Child {
105             handle: handle,
106             stdin: io.stdin.map(ChildStdin::from_inner),
107             stdout: io.stdout.map(ChildStdout::from_inner),
108             stderr: io.stderr.map(ChildStderr::from_inner),
109         }
110     }
111 }
112
113 impl IntoInner<imp::Process> for Child {
114     fn into_inner(self) -> imp::Process { self.handle }
115 }
116
117 #[stable(feature = "std_debug", since = "1.16.0")]
118 impl fmt::Debug for Child {
119     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120         f.debug_struct("Child")
121             .field("stdin", &self.stdin)
122             .field("stdout", &self.stdout)
123             .field("stderr", &self.stderr)
124             .finish()
125     }
126 }
127
128 /// A handle to a child process's stdin. This struct is used in the [`stdin`]
129 /// field on [`Child`].
130 ///
131 /// [`Child`]: struct.Child.html
132 /// [`stdin`]: struct.Child.html#structfield.stdin
133 #[stable(feature = "process", since = "1.0.0")]
134 pub struct ChildStdin {
135     inner: AnonPipe
136 }
137
138 #[stable(feature = "process", since = "1.0.0")]
139 impl Write for ChildStdin {
140     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
141         self.inner.write(buf)
142     }
143
144     fn flush(&mut self) -> io::Result<()> {
145         Ok(())
146     }
147 }
148
149 impl AsInner<AnonPipe> for ChildStdin {
150     fn as_inner(&self) -> &AnonPipe { &self.inner }
151 }
152
153 impl IntoInner<AnonPipe> for ChildStdin {
154     fn into_inner(self) -> AnonPipe { self.inner }
155 }
156
157 impl FromInner<AnonPipe> for ChildStdin {
158     fn from_inner(pipe: AnonPipe) -> ChildStdin {
159         ChildStdin { inner: pipe }
160     }
161 }
162
163 #[stable(feature = "std_debug", since = "1.16.0")]
164 impl fmt::Debug for ChildStdin {
165     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166         f.pad("ChildStdin { .. }")
167     }
168 }
169
170 /// A handle to a child process's stdout. This struct is used in the [`stdout`]
171 /// field on [`Child`].
172 ///
173 /// [`Child`]: struct.Child.html
174 /// [`stdout`]: struct.Child.html#structfield.stdout
175 #[stable(feature = "process", since = "1.0.0")]
176 pub struct ChildStdout {
177     inner: AnonPipe
178 }
179
180 #[stable(feature = "process", since = "1.0.0")]
181 impl Read for ChildStdout {
182     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
183         self.inner.read(buf)
184     }
185     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
186         self.inner.read_to_end(buf)
187     }
188 }
189
190 impl AsInner<AnonPipe> for ChildStdout {
191     fn as_inner(&self) -> &AnonPipe { &self.inner }
192 }
193
194 impl IntoInner<AnonPipe> for ChildStdout {
195     fn into_inner(self) -> AnonPipe { self.inner }
196 }
197
198 impl FromInner<AnonPipe> for ChildStdout {
199     fn from_inner(pipe: AnonPipe) -> ChildStdout {
200         ChildStdout { inner: pipe }
201     }
202 }
203
204 #[stable(feature = "std_debug", since = "1.16.0")]
205 impl fmt::Debug for ChildStdout {
206     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207         f.pad("ChildStdout { .. }")
208     }
209 }
210
211 /// A handle to a child process's stderr. This struct is used in the [`stderr`]
212 /// field on [`Child`].
213 ///
214 /// [`Child`]: struct.Child.html
215 /// [`stderr`]: struct.Child.html#structfield.stderr
216 #[stable(feature = "process", since = "1.0.0")]
217 pub struct ChildStderr {
218     inner: AnonPipe
219 }
220
221 #[stable(feature = "process", since = "1.0.0")]
222 impl Read for ChildStderr {
223     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
224         self.inner.read(buf)
225     }
226     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
227         self.inner.read_to_end(buf)
228     }
229 }
230
231 impl AsInner<AnonPipe> for ChildStderr {
232     fn as_inner(&self) -> &AnonPipe { &self.inner }
233 }
234
235 impl IntoInner<AnonPipe> for ChildStderr {
236     fn into_inner(self) -> AnonPipe { self.inner }
237 }
238
239 impl FromInner<AnonPipe> for ChildStderr {
240     fn from_inner(pipe: AnonPipe) -> ChildStderr {
241         ChildStderr { inner: pipe }
242     }
243 }
244
245 #[stable(feature = "std_debug", since = "1.16.0")]
246 impl fmt::Debug for ChildStderr {
247     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248         f.pad("ChildStderr { .. }")
249     }
250 }
251
252 /// A process builder, providing fine-grained control
253 /// over how a new process should be spawned.
254 ///
255 /// A default configuration can be
256 /// generated using `Command::new(program)`, where `program` gives a path to the
257 /// program to be executed. Additional builder methods allow the configuration
258 /// to be changed (for example, by adding arguments) prior to spawning:
259 ///
260 /// ```
261 /// use std::process::Command;
262 ///
263 /// let output = if cfg!(target_os = "windows") {
264 ///     Command::new("cmd")
265 ///             .args(&["/C", "echo hello"])
266 ///             .output()
267 ///             .expect("failed to execute process")
268 /// } else {
269 ///     Command::new("sh")
270 ///             .arg("-c")
271 ///             .arg("echo hello")
272 ///             .output()
273 ///             .expect("failed to execute process")
274 /// };
275 ///
276 /// let hello = output.stdout;
277 /// ```
278 #[stable(feature = "process", since = "1.0.0")]
279 pub struct Command {
280     inner: imp::Command,
281 }
282
283 impl Command {
284     /// Constructs a new `Command` for launching the program at
285     /// path `program`, with the following default configuration:
286     ///
287     /// * No arguments to the program
288     /// * Inherit the current process's environment
289     /// * Inherit the current process's working directory
290     /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
291     ///
292     /// Builder methods are provided to change these defaults and
293     /// otherwise configure the process.
294     ///
295     /// If `program` is not an absolute path, the `PATH` will be searched in
296     /// an OS-defined way.
297     ///
298     /// The search path to be used may be controlled by setting the
299     /// `PATH` environment variable on the Command,
300     /// but this has some implementation limitations on Windows
301     /// (see https://github.com/rust-lang/rust/issues/37519).
302     ///
303     /// # Examples
304     ///
305     /// Basic usage:
306     ///
307     /// ```no_run
308     /// use std::process::Command;
309     ///
310     /// Command::new("sh")
311     ///         .spawn()
312     ///         .expect("sh command failed to start");
313     /// ```
314     #[stable(feature = "process", since = "1.0.0")]
315     pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
316         Command { inner: imp::Command::new(program.as_ref()) }
317     }
318
319     /// Add an argument to pass to the program.
320     ///
321     /// # Examples
322     ///
323     /// Basic usage:
324     ///
325     /// ```no_run
326     /// use std::process::Command;
327     ///
328     /// Command::new("ls")
329     ///         .arg("-l")
330     ///         .arg("-a")
331     ///         .spawn()
332     ///         .expect("ls command failed to start");
333     /// ```
334     #[stable(feature = "process", since = "1.0.0")]
335     pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
336         self.inner.arg(arg.as_ref());
337         self
338     }
339
340     /// Add multiple arguments to pass to the program.
341     ///
342     /// # Examples
343     ///
344     /// Basic usage:
345     ///
346     /// ```no_run
347     /// use std::process::Command;
348     ///
349     /// Command::new("ls")
350     ///         .args(&["-l", "-a"])
351     ///         .spawn()
352     ///         .expect("ls command failed to start");
353     /// ```
354     #[stable(feature = "process", since = "1.0.0")]
355     pub fn args<I, S>(&mut self, args: I) -> &mut Command
356         where I: IntoIterator<Item=S>, S: AsRef<OsStr>
357     {
358         for arg in args {
359             self.arg(arg.as_ref());
360         }
361         self
362     }
363
364     /// Inserts or updates an environment variable mapping.
365     ///
366     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
367     /// and case-sensitive on all other platforms.
368     ///
369     /// # Examples
370     ///
371     /// Basic usage:
372     ///
373     /// ```no_run
374     /// use std::process::Command;
375     ///
376     /// Command::new("ls")
377     ///         .env("PATH", "/bin")
378     ///         .spawn()
379     ///         .expect("ls command failed to start");
380     /// ```
381     #[stable(feature = "process", since = "1.0.0")]
382     pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
383         where K: AsRef<OsStr>, V: AsRef<OsStr>
384     {
385         self.inner.env(key.as_ref(), val.as_ref());
386         self
387     }
388
389     /// Add or update multiple environment variable mappings.
390     ///
391     /// # Examples
392     ///
393     /// Basic usage:
394     /// ```no_run
395     /// use std::process::{Command, Stdio};
396     /// use std::env;
397     /// use std::collections::HashMap;
398     ///
399     /// let filtered_env : HashMap<String, String> =
400     ///     env::vars().filter(|&(ref k, _)|
401     ///         k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
402     ///     ).collect();
403     ///
404     /// Command::new("printenv")
405     ///         .stdin(Stdio::null())
406     ///         .stdout(Stdio::inherit())
407     ///         .env_clear()
408     ///         .envs(&filtered_env)
409     ///         .spawn()
410     ///         .expect("printenv failed to start");
411     /// ```
412     #[unstable(feature = "command_envs", issue = "38526")]
413     pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
414         where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
415     {
416         for (ref key, ref val) in vars {
417             self.inner.env(key.as_ref(), val.as_ref());
418         }
419         self
420     }
421
422     /// Removes an environment variable mapping.
423     ///
424     /// # Examples
425     ///
426     /// Basic usage:
427     ///
428     /// ```no_run
429     /// use std::process::Command;
430     ///
431     /// Command::new("ls")
432     ///         .env_remove("PATH")
433     ///         .spawn()
434     ///         .expect("ls command failed to start");
435     /// ```
436     #[stable(feature = "process", since = "1.0.0")]
437     pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
438         self.inner.env_remove(key.as_ref());
439         self
440     }
441
442     /// Clears the entire environment map for the child process.
443     ///
444     /// # Examples
445     ///
446     /// Basic usage:
447     ///
448     /// ```no_run
449     /// use std::process::Command;
450     ///
451     /// Command::new("ls")
452     ///         .env_clear()
453     ///         .spawn()
454     ///         .expect("ls command failed to start");
455     /// ```
456     #[stable(feature = "process", since = "1.0.0")]
457     pub fn env_clear(&mut self) -> &mut Command {
458         self.inner.env_clear();
459         self
460     }
461
462     /// Sets the working directory for the child process.
463     ///
464     /// # Examples
465     ///
466     /// Basic usage:
467     ///
468     /// ```no_run
469     /// use std::process::Command;
470     ///
471     /// Command::new("ls")
472     ///         .current_dir("/bin")
473     ///         .spawn()
474     ///         .expect("ls command failed to start");
475     /// ```
476     #[stable(feature = "process", since = "1.0.0")]
477     pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
478         self.inner.cwd(dir.as_ref().as_ref());
479         self
480     }
481
482     /// Configuration for the child process's stdin handle (file descriptor 0).
483     ///
484     /// # Examples
485     ///
486     /// Basic usage:
487     ///
488     /// ```no_run
489     /// use std::process::{Command, Stdio};
490     ///
491     /// Command::new("ls")
492     ///         .stdin(Stdio::null())
493     ///         .spawn()
494     ///         .expect("ls command failed to start");
495     /// ```
496     #[stable(feature = "process", since = "1.0.0")]
497     pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
498         self.inner.stdin(cfg.0);
499         self
500     }
501
502     /// Configuration for the child process's stdout handle (file descriptor 1).
503     ///
504     /// # Examples
505     ///
506     /// Basic usage:
507     ///
508     /// ```no_run
509     /// use std::process::{Command, Stdio};
510     ///
511     /// Command::new("ls")
512     ///         .stdout(Stdio::null())
513     ///         .spawn()
514     ///         .expect("ls command failed to start");
515     /// ```
516     #[stable(feature = "process", since = "1.0.0")]
517     pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
518         self.inner.stdout(cfg.0);
519         self
520     }
521
522     /// Configuration for the child process's stderr handle (file descriptor 2).
523     ///
524     /// # Examples
525     ///
526     /// Basic usage:
527     ///
528     /// ```no_run
529     /// use std::process::{Command, Stdio};
530     ///
531     /// Command::new("ls")
532     ///         .stderr(Stdio::null())
533     ///         .spawn()
534     ///         .expect("ls command failed to start");
535     /// ```
536     #[stable(feature = "process", since = "1.0.0")]
537     pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
538         self.inner.stderr(cfg.0);
539         self
540     }
541
542     /// Executes the command as a child process, returning a handle to it.
543     ///
544     /// By default, stdin, stdout and stderr are inherited from the parent.
545     ///
546     /// # Examples
547     ///
548     /// Basic usage:
549     ///
550     /// ```no_run
551     /// use std::process::Command;
552     ///
553     /// Command::new("ls")
554     ///         .spawn()
555     ///         .expect("ls command failed to start");
556     /// ```
557     #[stable(feature = "process", since = "1.0.0")]
558     pub fn spawn(&mut self) -> io::Result<Child> {
559         self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
560     }
561
562     /// Executes the command as a child process, waiting for it to finish and
563     /// collecting all of its output.
564     ///
565     /// By default, stdin, stdout and stderr are captured (and used to
566     /// provide the resulting output).
567     ///
568     /// # Examples
569     ///
570     /// ```should_panic
571     /// use std::process::Command;
572     /// let output = Command::new("/bin/cat")
573     ///                      .arg("file.txt")
574     ///                      .output()
575     ///                      .expect("failed to execute process");
576     ///
577     /// println!("status: {}", output.status);
578     /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
579     /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
580     ///
581     /// assert!(output.status.success());
582     /// ```
583     #[stable(feature = "process", since = "1.0.0")]
584     pub fn output(&mut self) -> io::Result<Output> {
585         self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
586             .and_then(|p| p.wait_with_output())
587     }
588
589     /// Executes a command as a child process, waiting for it to finish and
590     /// collecting its exit status.
591     ///
592     /// By default, stdin, stdout and stderr are inherited from the parent.
593     ///
594     /// # Examples
595     ///
596     /// ```should_panic
597     /// use std::process::Command;
598     ///
599     /// let status = Command::new("/bin/cat")
600     ///                      .arg("file.txt")
601     ///                      .status()
602     ///                      .expect("failed to execute process");
603     ///
604     /// println!("process exited with: {}", status);
605     ///
606     /// assert!(status.success());
607     /// ```
608     #[stable(feature = "process", since = "1.0.0")]
609     pub fn status(&mut self) -> io::Result<ExitStatus> {
610         self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
611                   .and_then(|mut p| p.wait())
612     }
613 }
614
615 #[stable(feature = "rust1", since = "1.0.0")]
616 impl fmt::Debug for Command {
617     /// Format the program and arguments of a Command for display. Any
618     /// non-utf8 data is lossily converted using the utf8 replacement
619     /// character.
620     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
621         self.inner.fmt(f)
622     }
623 }
624
625 impl AsInner<imp::Command> for Command {
626     fn as_inner(&self) -> &imp::Command { &self.inner }
627 }
628
629 impl AsInnerMut<imp::Command> for Command {
630     fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
631 }
632
633 /// The output of a finished process.
634 #[derive(PartialEq, Eq, Clone)]
635 #[stable(feature = "process", since = "1.0.0")]
636 pub struct Output {
637     /// The status (exit code) of the process.
638     #[stable(feature = "process", since = "1.0.0")]
639     pub status: ExitStatus,
640     /// The data that the process wrote to stdout.
641     #[stable(feature = "process", since = "1.0.0")]
642     pub stdout: Vec<u8>,
643     /// The data that the process wrote to stderr.
644     #[stable(feature = "process", since = "1.0.0")]
645     pub stderr: Vec<u8>,
646 }
647
648 // If either stderr or stdout are valid utf8 strings it prints the valid
649 // strings, otherwise it prints the byte sequence instead
650 #[stable(feature = "process_output_debug", since = "1.7.0")]
651 impl fmt::Debug for Output {
652     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
653
654         let stdout_utf8 = str::from_utf8(&self.stdout);
655         let stdout_debug: &fmt::Debug = match stdout_utf8 {
656             Ok(ref str) => str,
657             Err(_) => &self.stdout
658         };
659
660         let stderr_utf8 = str::from_utf8(&self.stderr);
661         let stderr_debug: &fmt::Debug = match stderr_utf8 {
662             Ok(ref str) => str,
663             Err(_) => &self.stderr
664         };
665
666         fmt.debug_struct("Output")
667             .field("status", &self.status)
668             .field("stdout", stdout_debug)
669             .field("stderr", stderr_debug)
670             .finish()
671     }
672 }
673
674 /// Describes what to do with a standard I/O stream for a child process.
675 #[stable(feature = "process", since = "1.0.0")]
676 pub struct Stdio(imp::Stdio);
677
678 impl Stdio {
679     /// A new pipe should be arranged to connect the parent and child processes.
680     #[stable(feature = "process", since = "1.0.0")]
681     pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
682
683     /// The child inherits from the corresponding parent descriptor.
684     #[stable(feature = "process", since = "1.0.0")]
685     pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
686
687     /// This stream will be ignored. This is the equivalent of attaching the
688     /// stream to `/dev/null`
689     #[stable(feature = "process", since = "1.0.0")]
690     pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
691 }
692
693 impl FromInner<imp::Stdio> for Stdio {
694     fn from_inner(inner: imp::Stdio) -> Stdio {
695         Stdio(inner)
696     }
697 }
698
699 #[stable(feature = "std_debug", since = "1.16.0")]
700 impl fmt::Debug for Stdio {
701     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
702         f.pad("Stdio { .. }")
703     }
704 }
705
706 /// Describes the result of a process after it has terminated.
707 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
708 #[stable(feature = "process", since = "1.0.0")]
709 pub struct ExitStatus(imp::ExitStatus);
710
711 impl ExitStatus {
712     /// Was termination successful? Signal termination not considered a success,
713     /// and success is defined as a zero exit status.
714     ///
715     /// # Examples
716     ///
717     /// ```rust,no_run
718     /// use std::process::Command;
719     ///
720     /// let status = Command::new("mkdir")
721     ///                      .arg("projects")
722     ///                      .status()
723     ///                      .expect("failed to execute mkdir");
724     ///
725     /// if status.success() {
726     ///     println!("'projects/' directory created");
727     /// } else {
728     ///     println!("failed to create 'projects/' directory");
729     /// }
730     /// ```
731     #[stable(feature = "process", since = "1.0.0")]
732     pub fn success(&self) -> bool {
733         self.0.success()
734     }
735
736     /// Returns the exit code of the process, if any.
737     ///
738     /// On Unix, this will return `None` if the process was terminated
739     /// by a signal; `std::os::unix` provides an extension trait for
740     /// extracting the signal and other details from the `ExitStatus`.
741     #[stable(feature = "process", since = "1.0.0")]
742     pub fn code(&self) -> Option<i32> {
743         self.0.code()
744     }
745 }
746
747 impl AsInner<imp::ExitStatus> for ExitStatus {
748     fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
749 }
750
751 impl FromInner<imp::ExitStatus> for ExitStatus {
752     fn from_inner(s: imp::ExitStatus) -> ExitStatus {
753         ExitStatus(s)
754     }
755 }
756
757 #[stable(feature = "process", since = "1.0.0")]
758 impl fmt::Display for ExitStatus {
759     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
760         self.0.fmt(f)
761     }
762 }
763
764 impl Child {
765     /// Forces the child to exit. This is equivalent to sending a
766     /// SIGKILL on unix platforms.
767     ///
768     /// # Examples
769     ///
770     /// Basic usage:
771     ///
772     /// ```no_run
773     /// use std::process::Command;
774     ///
775     /// let mut command = Command::new("yes");
776     /// if let Ok(mut child) = command.spawn() {
777     ///     child.kill().expect("command wasn't running");
778     /// } else {
779     ///     println!("yes command didn't start");
780     /// }
781     /// ```
782     #[stable(feature = "process", since = "1.0.0")]
783     pub fn kill(&mut self) -> io::Result<()> {
784         self.handle.kill()
785     }
786
787     /// Returns the OS-assigned process identifier associated with this child.
788     ///
789     /// # Examples
790     ///
791     /// Basic usage:
792     ///
793     /// ```no_run
794     /// use std::process::Command;
795     ///
796     /// let mut command = Command::new("ls");
797     /// if let Ok(child) = command.spawn() {
798     ///     println!("Child's id is {}", child.id());
799     /// } else {
800     ///     println!("ls command didn't start");
801     /// }
802     /// ```
803     #[stable(feature = "process_id", since = "1.3.0")]
804     pub fn id(&self) -> u32 {
805         self.handle.id()
806     }
807
808     /// Waits for the child to exit completely, returning the status that it
809     /// exited with. This function will continue to have the same return value
810     /// after it has been called at least once.
811     ///
812     /// The stdin handle to the child process, if any, will be closed
813     /// before waiting. This helps avoid deadlock: it ensures that the
814     /// child does not block waiting for input from the parent, while
815     /// the parent waits for the child to exit.
816     ///
817     /// # Examples
818     ///
819     /// Basic usage:
820     ///
821     /// ```no_run
822     /// use std::process::Command;
823     ///
824     /// let mut command = Command::new("ls");
825     /// if let Ok(mut child) = command.spawn() {
826     ///     child.wait().expect("command wasn't running");
827     ///     println!("Child has finished its execution!");
828     /// } else {
829     ///     println!("ls command didn't start");
830     /// }
831     /// ```
832     #[stable(feature = "process", since = "1.0.0")]
833     pub fn wait(&mut self) -> io::Result<ExitStatus> {
834         drop(self.stdin.take());
835         self.handle.wait().map(ExitStatus)
836     }
837
838     /// Attempts to collect the exit status of the child if it has already
839     /// exited.
840     ///
841     /// This function will not block the calling thread and will only advisorily
842     /// check to see if the child process has exited or not. If the child has
843     /// exited then on Unix the process id is reaped. This function is
844     /// guaranteed to repeatedly return a successful exit status so long as the
845     /// child has already exited.
846     ///
847     /// If the child has exited, then `Ok(Some(status))` is returned. If the
848     /// exit status is not available at this time then `Ok(None)` is returned.
849     /// If an error occurs, then that error is returned.
850     ///
851     /// Note that unlike `wait`, this function will not attempt to drop stdin.
852     ///
853     /// # Examples
854     ///
855     /// Basic usage:
856     ///
857     /// ```no_run
858     /// #![feature(process_try_wait)]
859     ///
860     /// use std::process::Command;
861     ///
862     /// let mut child = Command::new("ls").spawn().unwrap();
863     ///
864     /// match child.try_wait() {
865     ///     Ok(Some(status)) => println!("exited with: {}", status),
866     ///     Ok(None) => {
867     ///         println!("status not ready yet, let's really wait");
868     ///         let res = child.wait();
869     ///         println!("result: {:?}", res);
870     ///     }
871     ///     Err(e) => println!("error attempting to wait: {}", e),
872     /// }
873     /// ```
874     #[unstable(feature = "process_try_wait", issue = "38903")]
875     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
876         Ok(self.handle.try_wait()?.map(ExitStatus))
877     }
878
879     /// Simultaneously waits for the child to exit and collect all remaining
880     /// output on the stdout/stderr handles, returning an `Output`
881     /// instance.
882     ///
883     /// The stdin handle to the child process, if any, will be closed
884     /// before waiting. This helps avoid deadlock: it ensures that the
885     /// child does not block waiting for input from the parent, while
886     /// the parent waits for the child to exit.
887     ///
888     /// By default, stdin, stdout and stderr are inherited from the parent.
889     /// In order to capture the output into this `Result<Output>` it is
890     /// necessary to create new pipes between parent and child. Use
891     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
892     ///
893     /// # Examples
894     ///
895     /// ```should_panic
896     /// use std::process::{Command, Stdio};
897     ///
898     /// let child = Command::new("/bin/cat")
899     ///     .arg("file.txt")
900     ///     .stdout(Stdio::piped())
901     ///     .spawn()
902     ///     .expect("failed to execute child");
903     ///
904     /// let output = child
905     ///     .wait_with_output()
906     ///     .expect("failed to wait on child");
907     ///
908     /// assert!(output.status.success());
909     /// ```
910     ///
911     #[stable(feature = "process", since = "1.0.0")]
912     pub fn wait_with_output(mut self) -> io::Result<Output> {
913         drop(self.stdin.take());
914
915         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
916         match (self.stdout.take(), self.stderr.take()) {
917             (None, None) => {}
918             (Some(mut out), None) => {
919                 let res = out.read_to_end(&mut stdout);
920                 res.unwrap();
921             }
922             (None, Some(mut err)) => {
923                 let res = err.read_to_end(&mut stderr);
924                 res.unwrap();
925             }
926             (Some(out), Some(err)) => {
927                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
928                 res.unwrap();
929             }
930         }
931
932         let status = self.wait()?;
933         Ok(Output {
934             status: status,
935             stdout: stdout,
936             stderr: stderr,
937         })
938     }
939 }
940
941 /// Terminates the current process with the specified exit code.
942 ///
943 /// This function will never return and will immediately terminate the current
944 /// process. The exit code is passed through to the underlying OS and will be
945 /// available for consumption by another process.
946 ///
947 /// Note that because this function never returns, and that it terminates the
948 /// process, no destructors on the current stack or any other thread's stack
949 /// will be run. If a clean shutdown is needed it is recommended to only call
950 /// this function at a known point where there are no more destructors left
951 /// to run.
952 ///
953 /// ## Platform-specific behavior
954 ///
955 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
956 /// will be visible to a parent process inspecting the exit code. On most
957 /// Unix-like platforms, only the eight least-significant bits are considered.
958 ///
959 /// # Examples
960 ///
961 /// Due to this function’s behavior regarding destructors, a conventional way
962 /// to use the function is to extract the actual computation to another
963 /// function and compute the exit code from its return value:
964 ///
965 /// ```
966 /// use std::io::{self, Write};
967 ///
968 /// fn run_app() -> Result<(), ()> {
969 ///     // Application logic here
970 ///     Ok(())
971 /// }
972 ///
973 /// fn main() {
974 ///     ::std::process::exit(match run_app() {
975 ///        Ok(_) => 0,
976 ///        Err(err) => {
977 ///            writeln!(io::stderr(), "error: {:?}", err).unwrap();
978 ///            1
979 ///        }
980 ///     });
981 /// }
982 /// ```
983 ///
984 /// Due to [platform-specific behavior], the exit code for this example will be
985 /// `0` on Linux, but `256` on Windows:
986 ///
987 /// ```no_run
988 /// use std::process;
989 ///
990 /// process::exit(0x0f00);
991 /// ```
992 ///
993 /// [platform-specific behavior]: #platform-specific-behavior
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn exit(code: i32) -> ! {
996     ::sys_common::cleanup();
997     ::sys::os::exit(code)
998 }
999
1000 /// Terminates the process in an abnormal fashion.
1001 ///
1002 /// The function will never return and will immediately terminate the current
1003 /// process in a platform specific "abnormal" manner.
1004 ///
1005 /// Note that because this function never returns, and that it terminates the
1006 /// process, no destructors on the current stack or any other thread's stack
1007 /// will be run. If a clean shutdown is needed it is recommended to only call
1008 /// this function at a known point where there are no more destructors left
1009 /// to run.
1010 #[unstable(feature = "process_abort", issue = "37838")]
1011 pub fn abort() -> ! {
1012     unsafe { ::sys::abort_internal() };
1013 }
1014
1015 #[cfg(all(test, not(target_os = "emscripten")))]
1016 mod tests {
1017     use io::prelude::*;
1018
1019     use io::ErrorKind;
1020     use str;
1021     use super::{Command, Output, Stdio};
1022
1023     // FIXME(#10380) these tests should not all be ignored on android.
1024
1025     #[test]
1026     #[cfg_attr(target_os = "android", ignore)]
1027     fn smoke() {
1028         let p = if cfg!(target_os = "windows") {
1029             Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1030         } else {
1031             Command::new("true").spawn()
1032         };
1033         assert!(p.is_ok());
1034         let mut p = p.unwrap();
1035         assert!(p.wait().unwrap().success());
1036     }
1037
1038     #[test]
1039     #[cfg_attr(target_os = "android", ignore)]
1040     fn smoke_failure() {
1041         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1042             Ok(..) => panic!(),
1043             Err(..) => {}
1044         }
1045     }
1046
1047     #[test]
1048     #[cfg_attr(target_os = "android", ignore)]
1049     fn exit_reported_right() {
1050         let p = if cfg!(target_os = "windows") {
1051             Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1052         } else {
1053             Command::new("false").spawn()
1054         };
1055         assert!(p.is_ok());
1056         let mut p = p.unwrap();
1057         assert!(p.wait().unwrap().code() == Some(1));
1058         drop(p.wait());
1059     }
1060
1061     #[test]
1062     #[cfg(unix)]
1063     #[cfg_attr(target_os = "android", ignore)]
1064     fn signal_reported_right() {
1065         use os::unix::process::ExitStatusExt;
1066
1067         let mut p = Command::new("/bin/sh")
1068                             .arg("-c").arg("read a")
1069                             .stdin(Stdio::piped())
1070                             .spawn().unwrap();
1071         p.kill().unwrap();
1072         match p.wait().unwrap().signal() {
1073             Some(9) => {},
1074             result => panic!("not terminated by signal 9 (instead, {:?})",
1075                              result),
1076         }
1077     }
1078
1079     pub fn run_output(mut cmd: Command) -> String {
1080         let p = cmd.spawn();
1081         assert!(p.is_ok());
1082         let mut p = p.unwrap();
1083         assert!(p.stdout.is_some());
1084         let mut ret = String::new();
1085         p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1086         assert!(p.wait().unwrap().success());
1087         return ret;
1088     }
1089
1090     #[test]
1091     #[cfg_attr(target_os = "android", ignore)]
1092     fn stdout_works() {
1093         if cfg!(target_os = "windows") {
1094             let mut cmd = Command::new("cmd");
1095             cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1096             assert_eq!(run_output(cmd), "foobar\r\n");
1097         } else {
1098             let mut cmd = Command::new("echo");
1099             cmd.arg("foobar").stdout(Stdio::piped());
1100             assert_eq!(run_output(cmd), "foobar\n");
1101         }
1102     }
1103
1104     #[test]
1105     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1106     fn set_current_dir_works() {
1107         let mut cmd = Command::new("/bin/sh");
1108         cmd.arg("-c").arg("pwd")
1109            .current_dir("/")
1110            .stdout(Stdio::piped());
1111         assert_eq!(run_output(cmd), "/\n");
1112     }
1113
1114     #[test]
1115     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1116     fn stdin_works() {
1117         let mut p = Command::new("/bin/sh")
1118                             .arg("-c").arg("read line; echo $line")
1119                             .stdin(Stdio::piped())
1120                             .stdout(Stdio::piped())
1121                             .spawn().unwrap();
1122         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1123         drop(p.stdin.take());
1124         let mut out = String::new();
1125         p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1126         assert!(p.wait().unwrap().success());
1127         assert_eq!(out, "foobar\n");
1128     }
1129
1130
1131     #[test]
1132     #[cfg_attr(target_os = "android", ignore)]
1133     #[cfg(unix)]
1134     fn uid_works() {
1135         use os::unix::prelude::*;
1136         use libc;
1137         let mut p = Command::new("/bin/sh")
1138                             .arg("-c").arg("true")
1139                             .uid(unsafe { libc::getuid() })
1140                             .gid(unsafe { libc::getgid() })
1141                             .spawn().unwrap();
1142         assert!(p.wait().unwrap().success());
1143     }
1144
1145     #[test]
1146     #[cfg_attr(target_os = "android", ignore)]
1147     #[cfg(unix)]
1148     fn uid_to_root_fails() {
1149         use os::unix::prelude::*;
1150         use libc;
1151
1152         // if we're already root, this isn't a valid test. Most of the bots run
1153         // as non-root though (android is an exception).
1154         if unsafe { libc::getuid() == 0 } { return }
1155         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1156     }
1157
1158     #[test]
1159     #[cfg_attr(target_os = "android", ignore)]
1160     fn test_process_status() {
1161         let mut status = if cfg!(target_os = "windows") {
1162             Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1163         } else {
1164             Command::new("false").status().unwrap()
1165         };
1166         assert!(status.code() == Some(1));
1167
1168         status = if cfg!(target_os = "windows") {
1169             Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1170         } else {
1171             Command::new("true").status().unwrap()
1172         };
1173         assert!(status.success());
1174     }
1175
1176     #[test]
1177     fn test_process_output_fail_to_start() {
1178         match Command::new("/no-binary-by-this-name-should-exist").output() {
1179             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1180             Ok(..) => panic!()
1181         }
1182     }
1183
1184     #[test]
1185     #[cfg_attr(target_os = "android", ignore)]
1186     fn test_process_output_output() {
1187         let Output {status, stdout, stderr}
1188              = if cfg!(target_os = "windows") {
1189                  Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1190              } else {
1191                  Command::new("echo").arg("hello").output().unwrap()
1192              };
1193         let output_str = str::from_utf8(&stdout).unwrap();
1194
1195         assert!(status.success());
1196         assert_eq!(output_str.trim().to_string(), "hello");
1197         assert_eq!(stderr, Vec::new());
1198     }
1199
1200     #[test]
1201     #[cfg_attr(target_os = "android", ignore)]
1202     fn test_process_output_error() {
1203         let Output {status, stdout, stderr}
1204              = if cfg!(target_os = "windows") {
1205                  Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1206              } else {
1207                  Command::new("mkdir").arg(".").output().unwrap()
1208              };
1209
1210         assert!(status.code() == Some(1));
1211         assert_eq!(stdout, Vec::new());
1212         assert!(!stderr.is_empty());
1213     }
1214
1215     #[test]
1216     #[cfg_attr(target_os = "android", ignore)]
1217     fn test_finish_once() {
1218         let mut prog = if cfg!(target_os = "windows") {
1219             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1220         } else {
1221             Command::new("false").spawn().unwrap()
1222         };
1223         assert!(prog.wait().unwrap().code() == Some(1));
1224     }
1225
1226     #[test]
1227     #[cfg_attr(target_os = "android", ignore)]
1228     fn test_finish_twice() {
1229         let mut prog = if cfg!(target_os = "windows") {
1230             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1231         } else {
1232             Command::new("false").spawn().unwrap()
1233         };
1234         assert!(prog.wait().unwrap().code() == Some(1));
1235         assert!(prog.wait().unwrap().code() == Some(1));
1236     }
1237
1238     #[test]
1239     #[cfg_attr(target_os = "android", ignore)]
1240     fn test_wait_with_output_once() {
1241         let prog = if cfg!(target_os = "windows") {
1242             Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1243         } else {
1244             Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1245         };
1246
1247         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1248         let output_str = str::from_utf8(&stdout).unwrap();
1249
1250         assert!(status.success());
1251         assert_eq!(output_str.trim().to_string(), "hello");
1252         assert_eq!(stderr, Vec::new());
1253     }
1254
1255     #[cfg(all(unix, not(target_os="android")))]
1256     pub fn env_cmd() -> Command {
1257         Command::new("env")
1258     }
1259     #[cfg(target_os="android")]
1260     pub fn env_cmd() -> Command {
1261         let mut cmd = Command::new("/system/bin/sh");
1262         cmd.arg("-c").arg("set");
1263         cmd
1264     }
1265
1266     #[cfg(windows)]
1267     pub fn env_cmd() -> Command {
1268         let mut cmd = Command::new("cmd");
1269         cmd.arg("/c").arg("set");
1270         cmd
1271     }
1272
1273     #[test]
1274     fn test_inherit_env() {
1275         use env;
1276
1277         let result = env_cmd().output().unwrap();
1278         let output = String::from_utf8(result.stdout).unwrap();
1279
1280         for (ref k, ref v) in env::vars() {
1281             // don't check android RANDOM variables
1282             if cfg!(target_os = "android") && *k == "RANDOM" {
1283                 continue
1284             }
1285
1286             // Windows has hidden environment variables whose names start with
1287             // equals signs (`=`). Those do not show up in the output of the
1288             // `set` command.
1289             assert!((cfg!(windows) && k.starts_with("=")) ||
1290                     k.starts_with("DYLD") ||
1291                     output.contains(&format!("{}={}", *k, *v)) ||
1292                     output.contains(&format!("{}='{}'", *k, *v)),
1293                     "output doesn't contain `{}={}`\n{}",
1294                     k, v, output);
1295         }
1296     }
1297
1298     #[test]
1299     fn test_override_env() {
1300         use env;
1301
1302         // In some build environments (such as chrooted Nix builds), `env` can
1303         // only be found in the explicitly-provided PATH env variable, not in
1304         // default places such as /bin or /usr/bin. So we need to pass through
1305         // PATH to our sub-process.
1306         let mut cmd = env_cmd();
1307         cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1308         if let Some(p) = env::var_os("PATH") {
1309             cmd.env("PATH", &p);
1310         }
1311         let result = cmd.output().unwrap();
1312         let output = String::from_utf8_lossy(&result.stdout).to_string();
1313
1314         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1315                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1316     }
1317
1318     #[test]
1319     fn test_add_to_env() {
1320         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1321         let output = String::from_utf8_lossy(&result.stdout).to_string();
1322
1323         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1324                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1325     }
1326
1327     // Regression tests for #30858.
1328     #[test]
1329     fn test_interior_nul_in_progname_is_error() {
1330         match Command::new("has-some-\0\0s-inside").spawn() {
1331             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1332             Ok(_) => panic!(),
1333         }
1334     }
1335
1336     #[test]
1337     fn test_interior_nul_in_arg_is_error() {
1338         match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1339             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1340             Ok(_) => panic!(),
1341         }
1342     }
1343
1344     #[test]
1345     fn test_interior_nul_in_args_is_error() {
1346         match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1347             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1348             Ok(_) => panic!(),
1349         }
1350     }
1351
1352     #[test]
1353     fn test_interior_nul_in_current_dir_is_error() {
1354         match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1355             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1356             Ok(_) => panic!(),
1357         }
1358     }
1359
1360     // Regression tests for #30862.
1361     #[test]
1362     fn test_interior_nul_in_env_key_is_error() {
1363         match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1364             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1365             Ok(_) => panic!(),
1366         }
1367     }
1368
1369     #[test]
1370     fn test_interior_nul_in_env_value_is_error() {
1371         match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1372             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1373             Ok(_) => panic!(),
1374         }
1375     }
1376
1377     /// Test that process creation flags work by debugging a process.
1378     /// Other creation flags make it hard or impossible to detect
1379     /// behavioral changes in the process.
1380     #[test]
1381     #[cfg(windows)]
1382     fn test_creation_flags() {
1383         use os::windows::process::CommandExt;
1384         use sys::c::{BOOL, DWORD, INFINITE};
1385         #[repr(C, packed)]
1386         struct DEBUG_EVENT {
1387             pub event_code: DWORD,
1388             pub process_id: DWORD,
1389             pub thread_id: DWORD,
1390             // This is a union in the real struct, but we don't
1391             // need this data for the purposes of this test.
1392             pub _junk: [u8; 164],
1393         }
1394
1395         extern "system" {
1396             fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1397             fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1398                                   dwContinueStatus: DWORD) -> BOOL;
1399         }
1400
1401         const DEBUG_PROCESS: DWORD = 1;
1402         const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1403         const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1404
1405         let mut child = Command::new("cmd")
1406             .creation_flags(DEBUG_PROCESS)
1407             .stdin(Stdio::piped()).spawn().unwrap();
1408         child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1409         let mut events = 0;
1410         let mut event = DEBUG_EVENT {
1411             event_code: 0,
1412             process_id: 0,
1413             thread_id: 0,
1414             _junk: [0; 164],
1415         };
1416         loop {
1417             if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1418                 panic!("WaitForDebugEvent failed!");
1419             }
1420             events += 1;
1421
1422             if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1423                 break;
1424             }
1425
1426             if unsafe { ContinueDebugEvent(event.process_id,
1427                                            event.thread_id,
1428                                            DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1429                 panic!("ContinueDebugEvent failed!");
1430             }
1431         }
1432         assert!(events > 0);
1433     }
1434 }