]> git.lizzy.rs Git - rust.git/blob - src/libstd/process.rs
Unignore u128 test for stage 0,1
[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(status)` is returned. If the exit
848     /// status is not available at this time then an error is returned with the
849     /// error kind `WouldBlock`. 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::io;
861     /// use std::process::Command;
862     ///
863     /// let mut child = Command::new("ls").spawn().unwrap();
864     ///
865     /// match child.try_wait() {
866     ///     Ok(status) => println!("exited with: {}", status),
867     ///     Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
868     ///         println!("status not ready yet, let's really wait");
869     ///         let res = child.wait();
870     ///         println!("result: {:?}", res);
871     ///     }
872     ///     Err(e) => println!("error attempting to wait: {}", e),
873     /// }
874     /// ```
875     #[unstable(feature = "process_try_wait", issue = "38903")]
876     pub fn try_wait(&mut self) -> io::Result<ExitStatus> {
877         self.handle.try_wait().map(ExitStatus)
878     }
879
880     /// Simultaneously waits for the child to exit and collect all remaining
881     /// output on the stdout/stderr handles, returning an `Output`
882     /// instance.
883     ///
884     /// The stdin handle to the child process, if any, will be closed
885     /// before waiting. This helps avoid deadlock: it ensures that the
886     /// child does not block waiting for input from the parent, while
887     /// the parent waits for the child to exit.
888     ///
889     /// By default, stdin, stdout and stderr are inherited from the parent.
890     /// In order to capture the output into this `Result<Output>` it is
891     /// necessary to create new pipes between parent and child. Use
892     /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
893     ///
894     /// # Examples
895     ///
896     /// ```should_panic
897     /// use std::process::{Command, Stdio};
898     ///
899     /// let child = Command::new("/bin/cat")
900     ///     .arg("file.txt")
901     ///     .stdout(Stdio::piped())
902     ///     .spawn()
903     ///     .expect("failed to execute child");
904     ///
905     /// let output = child
906     ///     .wait_with_output()
907     ///     .expect("failed to wait on child");
908     ///
909     /// assert!(output.status.success());
910     /// ```
911     ///
912     #[stable(feature = "process", since = "1.0.0")]
913     pub fn wait_with_output(mut self) -> io::Result<Output> {
914         drop(self.stdin.take());
915
916         let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
917         match (self.stdout.take(), self.stderr.take()) {
918             (None, None) => {}
919             (Some(mut out), None) => {
920                 let res = out.read_to_end(&mut stdout);
921                 res.unwrap();
922             }
923             (None, Some(mut err)) => {
924                 let res = err.read_to_end(&mut stderr);
925                 res.unwrap();
926             }
927             (Some(out), Some(err)) => {
928                 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
929                 res.unwrap();
930             }
931         }
932
933         let status = self.wait()?;
934         Ok(Output {
935             status: status,
936             stdout: stdout,
937             stderr: stderr,
938         })
939     }
940 }
941
942 /// Terminates the current process with the specified exit code.
943 ///
944 /// This function will never return and will immediately terminate the current
945 /// process. The exit code is passed through to the underlying OS and will be
946 /// available for consumption by another process.
947 ///
948 /// Note that because this function never returns, and that it terminates the
949 /// process, no destructors on the current stack or any other thread's stack
950 /// will be run. If a clean shutdown is needed it is recommended to only call
951 /// this function at a known point where there are no more destructors left
952 /// to run.
953 ///
954 /// ## Platform-specific behavior
955 ///
956 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
957 /// will be visible to a parent process inspecting the exit code. On most
958 /// Unix-like platforms, only the eight least-significant bits are considered.
959 ///
960 /// # Examples
961 ///
962 /// Due to this function’s behavior regarding destructors, a conventional way
963 /// to use the function is to extract the actual computation to another
964 /// function and compute the exit code from its return value:
965 ///
966 /// ```
967 /// use std::io::{self, Write};
968 ///
969 /// fn run_app() -> Result<(), ()> {
970 ///     // Application logic here
971 ///     Ok(())
972 /// }
973 ///
974 /// fn main() {
975 ///     ::std::process::exit(match run_app() {
976 ///        Ok(_) => 0,
977 ///        Err(err) => {
978 ///            writeln!(io::stderr(), "error: {:?}", err).unwrap();
979 ///            1
980 ///        }
981 ///     });
982 /// }
983 /// ```
984 ///
985 /// Due to [platform-specific behavior], the exit code for this example will be
986 /// `0` on Linux, but `256` on Windows:
987 ///
988 /// ```no_run
989 /// use std::process;
990 ///
991 /// process::exit(0x0f00);
992 /// ```
993 ///
994 /// [platform-specific behavior]: #platform-specific-behavior
995 #[stable(feature = "rust1", since = "1.0.0")]
996 pub fn exit(code: i32) -> ! {
997     ::sys_common::cleanup();
998     ::sys::os::exit(code)
999 }
1000
1001 /// Terminates the process in an abnormal fashion.
1002 ///
1003 /// The function will never return and will immediately terminate the current
1004 /// process in a platform specific "abnormal" manner.
1005 ///
1006 /// Note that because this function never returns, and that it terminates the
1007 /// process, no destructors on the current stack or any other thread's stack
1008 /// will be run. If a clean shutdown is needed it is recommended to only call
1009 /// this function at a known point where there are no more destructors left
1010 /// to run.
1011 #[unstable(feature = "process_abort", issue = "37838")]
1012 pub fn abort() -> ! {
1013     unsafe { ::sys::abort_internal() };
1014 }
1015
1016 #[cfg(all(test, not(target_os = "emscripten")))]
1017 mod tests {
1018     use io::prelude::*;
1019
1020     use io::ErrorKind;
1021     use str;
1022     use super::{Command, Output, Stdio};
1023
1024     // FIXME(#10380) these tests should not all be ignored on android.
1025
1026     #[test]
1027     #[cfg_attr(target_os = "android", ignore)]
1028     fn smoke() {
1029         let p = if cfg!(target_os = "windows") {
1030             Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1031         } else {
1032             Command::new("true").spawn()
1033         };
1034         assert!(p.is_ok());
1035         let mut p = p.unwrap();
1036         assert!(p.wait().unwrap().success());
1037     }
1038
1039     #[test]
1040     #[cfg_attr(target_os = "android", ignore)]
1041     fn smoke_failure() {
1042         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1043             Ok(..) => panic!(),
1044             Err(..) => {}
1045         }
1046     }
1047
1048     #[test]
1049     #[cfg_attr(target_os = "android", ignore)]
1050     fn exit_reported_right() {
1051         let p = if cfg!(target_os = "windows") {
1052             Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1053         } else {
1054             Command::new("false").spawn()
1055         };
1056         assert!(p.is_ok());
1057         let mut p = p.unwrap();
1058         assert!(p.wait().unwrap().code() == Some(1));
1059         drop(p.wait());
1060     }
1061
1062     #[test]
1063     #[cfg(unix)]
1064     #[cfg_attr(target_os = "android", ignore)]
1065     fn signal_reported_right() {
1066         use os::unix::process::ExitStatusExt;
1067
1068         let mut p = Command::new("/bin/sh")
1069                             .arg("-c").arg("read a")
1070                             .stdin(Stdio::piped())
1071                             .spawn().unwrap();
1072         p.kill().unwrap();
1073         match p.wait().unwrap().signal() {
1074             Some(9) => {},
1075             result => panic!("not terminated by signal 9 (instead, {:?})",
1076                              result),
1077         }
1078     }
1079
1080     pub fn run_output(mut cmd: Command) -> String {
1081         let p = cmd.spawn();
1082         assert!(p.is_ok());
1083         let mut p = p.unwrap();
1084         assert!(p.stdout.is_some());
1085         let mut ret = String::new();
1086         p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1087         assert!(p.wait().unwrap().success());
1088         return ret;
1089     }
1090
1091     #[test]
1092     #[cfg_attr(target_os = "android", ignore)]
1093     fn stdout_works() {
1094         if cfg!(target_os = "windows") {
1095             let mut cmd = Command::new("cmd");
1096             cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1097             assert_eq!(run_output(cmd), "foobar\r\n");
1098         } else {
1099             let mut cmd = Command::new("echo");
1100             cmd.arg("foobar").stdout(Stdio::piped());
1101             assert_eq!(run_output(cmd), "foobar\n");
1102         }
1103     }
1104
1105     #[test]
1106     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1107     fn set_current_dir_works() {
1108         let mut cmd = Command::new("/bin/sh");
1109         cmd.arg("-c").arg("pwd")
1110            .current_dir("/")
1111            .stdout(Stdio::piped());
1112         assert_eq!(run_output(cmd), "/\n");
1113     }
1114
1115     #[test]
1116     #[cfg_attr(any(windows, target_os = "android"), ignore)]
1117     fn stdin_works() {
1118         let mut p = Command::new("/bin/sh")
1119                             .arg("-c").arg("read line; echo $line")
1120                             .stdin(Stdio::piped())
1121                             .stdout(Stdio::piped())
1122                             .spawn().unwrap();
1123         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1124         drop(p.stdin.take());
1125         let mut out = String::new();
1126         p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1127         assert!(p.wait().unwrap().success());
1128         assert_eq!(out, "foobar\n");
1129     }
1130
1131
1132     #[test]
1133     #[cfg_attr(target_os = "android", ignore)]
1134     #[cfg(unix)]
1135     fn uid_works() {
1136         use os::unix::prelude::*;
1137         use libc;
1138         let mut p = Command::new("/bin/sh")
1139                             .arg("-c").arg("true")
1140                             .uid(unsafe { libc::getuid() })
1141                             .gid(unsafe { libc::getgid() })
1142                             .spawn().unwrap();
1143         assert!(p.wait().unwrap().success());
1144     }
1145
1146     #[test]
1147     #[cfg_attr(target_os = "android", ignore)]
1148     #[cfg(unix)]
1149     fn uid_to_root_fails() {
1150         use os::unix::prelude::*;
1151         use libc;
1152
1153         // if we're already root, this isn't a valid test. Most of the bots run
1154         // as non-root though (android is an exception).
1155         if unsafe { libc::getuid() == 0 } { return }
1156         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1157     }
1158
1159     #[test]
1160     #[cfg_attr(target_os = "android", ignore)]
1161     fn test_process_status() {
1162         let mut status = if cfg!(target_os = "windows") {
1163             Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1164         } else {
1165             Command::new("false").status().unwrap()
1166         };
1167         assert!(status.code() == Some(1));
1168
1169         status = if cfg!(target_os = "windows") {
1170             Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1171         } else {
1172             Command::new("true").status().unwrap()
1173         };
1174         assert!(status.success());
1175     }
1176
1177     #[test]
1178     fn test_process_output_fail_to_start() {
1179         match Command::new("/no-binary-by-this-name-should-exist").output() {
1180             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1181             Ok(..) => panic!()
1182         }
1183     }
1184
1185     #[test]
1186     #[cfg_attr(target_os = "android", ignore)]
1187     fn test_process_output_output() {
1188         let Output {status, stdout, stderr}
1189              = if cfg!(target_os = "windows") {
1190                  Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1191              } else {
1192                  Command::new("echo").arg("hello").output().unwrap()
1193              };
1194         let output_str = str::from_utf8(&stdout).unwrap();
1195
1196         assert!(status.success());
1197         assert_eq!(output_str.trim().to_string(), "hello");
1198         assert_eq!(stderr, Vec::new());
1199     }
1200
1201     #[test]
1202     #[cfg_attr(target_os = "android", ignore)]
1203     fn test_process_output_error() {
1204         let Output {status, stdout, stderr}
1205              = if cfg!(target_os = "windows") {
1206                  Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1207              } else {
1208                  Command::new("mkdir").arg(".").output().unwrap()
1209              };
1210
1211         assert!(status.code() == Some(1));
1212         assert_eq!(stdout, Vec::new());
1213         assert!(!stderr.is_empty());
1214     }
1215
1216     #[test]
1217     #[cfg_attr(target_os = "android", ignore)]
1218     fn test_finish_once() {
1219         let mut prog = if cfg!(target_os = "windows") {
1220             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1221         } else {
1222             Command::new("false").spawn().unwrap()
1223         };
1224         assert!(prog.wait().unwrap().code() == Some(1));
1225     }
1226
1227     #[test]
1228     #[cfg_attr(target_os = "android", ignore)]
1229     fn test_finish_twice() {
1230         let mut prog = if cfg!(target_os = "windows") {
1231             Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1232         } else {
1233             Command::new("false").spawn().unwrap()
1234         };
1235         assert!(prog.wait().unwrap().code() == Some(1));
1236         assert!(prog.wait().unwrap().code() == Some(1));
1237     }
1238
1239     #[test]
1240     #[cfg_attr(target_os = "android", ignore)]
1241     fn test_wait_with_output_once() {
1242         let prog = if cfg!(target_os = "windows") {
1243             Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1244         } else {
1245             Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1246         };
1247
1248         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1249         let output_str = str::from_utf8(&stdout).unwrap();
1250
1251         assert!(status.success());
1252         assert_eq!(output_str.trim().to_string(), "hello");
1253         assert_eq!(stderr, Vec::new());
1254     }
1255
1256     #[cfg(all(unix, not(target_os="android")))]
1257     pub fn env_cmd() -> Command {
1258         Command::new("env")
1259     }
1260     #[cfg(target_os="android")]
1261     pub fn env_cmd() -> Command {
1262         let mut cmd = Command::new("/system/bin/sh");
1263         cmd.arg("-c").arg("set");
1264         cmd
1265     }
1266
1267     #[cfg(windows)]
1268     pub fn env_cmd() -> Command {
1269         let mut cmd = Command::new("cmd");
1270         cmd.arg("/c").arg("set");
1271         cmd
1272     }
1273
1274     #[test]
1275     fn test_inherit_env() {
1276         use env;
1277
1278         let result = env_cmd().output().unwrap();
1279         let output = String::from_utf8(result.stdout).unwrap();
1280
1281         for (ref k, ref v) in env::vars() {
1282             // don't check android RANDOM variables
1283             if cfg!(target_os = "android") && *k == "RANDOM" {
1284                 continue
1285             }
1286
1287             // Windows has hidden environment variables whose names start with
1288             // equals signs (`=`). Those do not show up in the output of the
1289             // `set` command.
1290             assert!((cfg!(windows) && k.starts_with("=")) ||
1291                     k.starts_with("DYLD") ||
1292                     output.contains(&format!("{}={}", *k, *v)) ||
1293                     output.contains(&format!("{}='{}'", *k, *v)),
1294                     "output doesn't contain `{}={}`\n{}",
1295                     k, v, output);
1296         }
1297     }
1298
1299     #[test]
1300     fn test_override_env() {
1301         use env;
1302
1303         // In some build environments (such as chrooted Nix builds), `env` can
1304         // only be found in the explicitly-provided PATH env variable, not in
1305         // default places such as /bin or /usr/bin. So we need to pass through
1306         // PATH to our sub-process.
1307         let mut cmd = env_cmd();
1308         cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1309         if let Some(p) = env::var_os("PATH") {
1310             cmd.env("PATH", &p);
1311         }
1312         let result = cmd.output().unwrap();
1313         let output = String::from_utf8_lossy(&result.stdout).to_string();
1314
1315         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1316                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1317     }
1318
1319     #[test]
1320     fn test_add_to_env() {
1321         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1322         let output = String::from_utf8_lossy(&result.stdout).to_string();
1323
1324         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1325                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1326     }
1327
1328     // Regression tests for #30858.
1329     #[test]
1330     fn test_interior_nul_in_progname_is_error() {
1331         match Command::new("has-some-\0\0s-inside").spawn() {
1332             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1333             Ok(_) => panic!(),
1334         }
1335     }
1336
1337     #[test]
1338     fn test_interior_nul_in_arg_is_error() {
1339         match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1340             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1341             Ok(_) => panic!(),
1342         }
1343     }
1344
1345     #[test]
1346     fn test_interior_nul_in_args_is_error() {
1347         match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1348             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1349             Ok(_) => panic!(),
1350         }
1351     }
1352
1353     #[test]
1354     fn test_interior_nul_in_current_dir_is_error() {
1355         match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1356             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1357             Ok(_) => panic!(),
1358         }
1359     }
1360
1361     // Regression tests for #30862.
1362     #[test]
1363     fn test_interior_nul_in_env_key_is_error() {
1364         match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1365             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1366             Ok(_) => panic!(),
1367         }
1368     }
1369
1370     #[test]
1371     fn test_interior_nul_in_env_value_is_error() {
1372         match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1373             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1374             Ok(_) => panic!(),
1375         }
1376     }
1377
1378     /// Test that process creation flags work by debugging a process.
1379     /// Other creation flags make it hard or impossible to detect
1380     /// behavioral changes in the process.
1381     #[test]
1382     #[cfg(windows)]
1383     fn test_creation_flags() {
1384         use os::windows::process::CommandExt;
1385         use sys::c::{BOOL, DWORD, INFINITE};
1386         #[repr(C, packed)]
1387         struct DEBUG_EVENT {
1388             pub event_code: DWORD,
1389             pub process_id: DWORD,
1390             pub thread_id: DWORD,
1391             // This is a union in the real struct, but we don't
1392             // need this data for the purposes of this test.
1393             pub _junk: [u8; 164],
1394         }
1395
1396         extern "system" {
1397             fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1398             fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1399                                   dwContinueStatus: DWORD) -> BOOL;
1400         }
1401
1402         const DEBUG_PROCESS: DWORD = 1;
1403         const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1404         const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1405
1406         let mut child = Command::new("cmd")
1407             .creation_flags(DEBUG_PROCESS)
1408             .stdin(Stdio::piped()).spawn().unwrap();
1409         child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1410         let mut events = 0;
1411         let mut event = DEBUG_EVENT {
1412             event_code: 0,
1413             process_id: 0,
1414             thread_id: 0,
1415             _junk: [0; 164],
1416         };
1417         loop {
1418             if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1419                 panic!("WaitForDebugEvent failed!");
1420             }
1421             events += 1;
1422
1423             if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1424                 break;
1425             }
1426
1427             if unsafe { ContinueDebugEvent(event.process_id,
1428                                            event.thread_id,
1429                                            DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1430                 panic!("ContinueDebugEvent failed!");
1431             }
1432         }
1433         assert!(events > 0);
1434     }
1435 }