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