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