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