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