]> git.lizzy.rs Git - rust.git/blob - src/libstd/process.rs
Add missing #[test] attribute to test
[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 //! Working with processes.
12
13 #![stable(feature = "process", since = "1.0.0")]
14 #![allow(non_upper_case_globals)]
15
16 use prelude::v1::*;
17 use io::prelude::*;
18
19 use ffi::OsStr;
20 use fmt;
21 use io::{self, Error, ErrorKind};
22 use path;
23 use sync::mpsc::{channel, Receiver};
24 use sys::pipe::{self, AnonPipe};
25 use sys::process as imp;
26 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
27 use thread;
28
29 /// Representation of a running or exited child process.
30 ///
31 /// This structure is used to represent and manage child processes. A child
32 /// process is created via the `Command` struct, which configures the spawning
33 /// process and can itself be constructed using a builder-style interface.
34 ///
35 /// # Examples
36 ///
37 /// ```should_panic
38 /// use std::process::Command;
39 ///
40 /// let mut child = Command::new("/bin/cat")
41 ///                         .arg("file.txt")
42 ///                         .spawn()
43 ///                         .unwrap_or_else(|e| { panic!("failed to execute child: {}", e) });
44 ///
45 /// let ecode = child.wait()
46 ///                  .unwrap_or_else(|e| { panic!("failed to wait on child: {}", e) });
47 ///
48 /// assert!(ecode.success());
49 /// ```
50 #[stable(feature = "process", since = "1.0.0")]
51 pub struct Child {
52     handle: imp::Process,
53
54     /// None until wait() or wait_with_output() is called.
55     status: Option<imp::ExitStatus>,
56
57     /// The handle for writing to the child's stdin, if it has been captured
58     #[stable(feature = "process", since = "1.0.0")]
59     pub stdin: Option<ChildStdin>,
60
61     /// The handle for reading from the child's stdout, if it has been captured
62     #[stable(feature = "process", since = "1.0.0")]
63     pub stdout: Option<ChildStdout>,
64
65     /// The handle for reading from the child's stderr, if it has been captured
66     #[stable(feature = "process", since = "1.0.0")]
67     pub stderr: Option<ChildStderr>,
68 }
69
70 impl AsInner<imp::Process> for Child {
71     fn as_inner(&self) -> &imp::Process { &self.handle }
72 }
73
74 impl IntoInner<imp::Process> for Child {
75     fn into_inner(self) -> imp::Process { self.handle }
76 }
77
78 /// A handle to a child process's stdin
79 #[stable(feature = "process", since = "1.0.0")]
80 pub struct ChildStdin {
81     inner: AnonPipe
82 }
83
84 #[stable(feature = "process", since = "1.0.0")]
85 impl Write for ChildStdin {
86     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
87         self.inner.write(buf)
88     }
89
90     fn flush(&mut self) -> io::Result<()> {
91         Ok(())
92     }
93 }
94
95 impl AsInner<AnonPipe> for ChildStdin {
96     fn as_inner(&self) -> &AnonPipe { &self.inner }
97 }
98
99 impl IntoInner<AnonPipe> for ChildStdin {
100     fn into_inner(self) -> AnonPipe { self.inner }
101 }
102
103 /// A handle to a child procesess's stdout
104 #[stable(feature = "process", since = "1.0.0")]
105 pub struct ChildStdout {
106     inner: AnonPipe
107 }
108
109 #[stable(feature = "process", since = "1.0.0")]
110 impl Read for ChildStdout {
111     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
112         self.inner.read(buf)
113     }
114 }
115
116 impl AsInner<AnonPipe> for ChildStdout {
117     fn as_inner(&self) -> &AnonPipe { &self.inner }
118 }
119
120 impl IntoInner<AnonPipe> for ChildStdout {
121     fn into_inner(self) -> AnonPipe { self.inner }
122 }
123
124 /// A handle to a child procesess's stderr
125 #[stable(feature = "process", since = "1.0.0")]
126 pub struct ChildStderr {
127     inner: AnonPipe
128 }
129
130 #[stable(feature = "process", since = "1.0.0")]
131 impl Read for ChildStderr {
132     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
133         self.inner.read(buf)
134     }
135 }
136
137 impl AsInner<AnonPipe> for ChildStderr {
138     fn as_inner(&self) -> &AnonPipe { &self.inner }
139 }
140
141 impl IntoInner<AnonPipe> for ChildStderr {
142     fn into_inner(self) -> AnonPipe { self.inner }
143 }
144
145 /// The `Command` type acts as a process builder, providing fine-grained control
146 /// over how a new process should be spawned. A default configuration can be
147 /// generated using `Command::new(program)`, where `program` gives a path to the
148 /// program to be executed. Additional builder methods allow the configuration
149 /// to be changed (for example, by adding arguments) prior to spawning:
150 ///
151 /// ```
152 /// use std::process::Command;
153 ///
154 /// let output = Command::new("sh")
155 ///                      .arg("-c")
156 ///                      .arg("echo hello")
157 ///                      .output()
158 ///                      .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
159 /// let hello = output.stdout;
160 /// ```
161 #[stable(feature = "process", since = "1.0.0")]
162 pub struct Command {
163     inner: imp::Command,
164
165     // Details explained in the builder methods
166     stdin: Option<Stdio>,
167     stdout: Option<Stdio>,
168     stderr: Option<Stdio>,
169 }
170
171 impl Command {
172     /// Constructs a new `Command` for launching the program at
173     /// path `program`, with the following default configuration:
174     ///
175     /// * No arguments to the program
176     /// * Inherit the current process's environment
177     /// * Inherit the current process's working directory
178     /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
179     ///
180     /// Builder methods are provided to change these defaults and
181     /// otherwise configure the process.
182     #[stable(feature = "process", since = "1.0.0")]
183     pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
184         Command {
185             inner: imp::Command::new(program.as_ref()),
186             stdin: None,
187             stdout: None,
188             stderr: None,
189         }
190     }
191
192     /// Add an argument to pass to the program.
193     #[stable(feature = "process", since = "1.0.0")]
194     pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
195         self.inner.arg(arg.as_ref());
196         self
197     }
198
199     /// Add multiple arguments to pass to the program.
200     #[stable(feature = "process", since = "1.0.0")]
201     pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut Command {
202         self.inner.args(args.iter().map(AsRef::as_ref));
203         self
204     }
205
206     /// Inserts or updates an environment variable mapping.
207     ///
208     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
209     /// and case-sensitive on all other platforms.
210     #[stable(feature = "process", since = "1.0.0")]
211     pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
212         where K: AsRef<OsStr>, V: AsRef<OsStr>
213     {
214         self.inner.env(key.as_ref(), val.as_ref());
215         self
216     }
217
218     /// Removes an environment variable mapping.
219     #[stable(feature = "process", since = "1.0.0")]
220     pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
221         self.inner.env_remove(key.as_ref());
222         self
223     }
224
225     /// Clears the entire environment map for the child process.
226     #[stable(feature = "process", since = "1.0.0")]
227     pub fn env_clear(&mut self) -> &mut Command {
228         self.inner.env_clear();
229         self
230     }
231
232     /// Sets the working directory for the child process.
233     #[stable(feature = "process", since = "1.0.0")]
234     pub fn current_dir<P: AsRef<path::Path>>(&mut self, dir: P) -> &mut Command {
235         self.inner.cwd(dir.as_ref().as_ref());
236         self
237     }
238
239     /// Configuration for the child process's stdin handle (file descriptor 0).
240     #[stable(feature = "process", since = "1.0.0")]
241     pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
242         self.stdin = Some(cfg);
243         self
244     }
245
246     /// Configuration for the child process's stdout handle (file descriptor 1).
247     #[stable(feature = "process", since = "1.0.0")]
248     pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
249         self.stdout = Some(cfg);
250         self
251     }
252
253     /// Configuration for the child process's stderr handle (file descriptor 2).
254     #[stable(feature = "process", since = "1.0.0")]
255     pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
256         self.stderr = Some(cfg);
257         self
258     }
259
260     fn spawn_inner(&self, default_io: StdioImp) -> io::Result<Child> {
261         let default_io = Stdio(default_io);
262
263         // See comment on `setup_io` for what `_drop_later` is.
264         let (their_stdin, our_stdin, _drop_later) = try!(
265             setup_io(self.stdin.as_ref().unwrap_or(&default_io), true)
266         );
267         let (their_stdout, our_stdout, _drop_later) = try!(
268             setup_io(self.stdout.as_ref().unwrap_or(&default_io), false)
269         );
270         let (their_stderr, our_stderr, _drop_later) = try!(
271             setup_io(self.stderr.as_ref().unwrap_or(&default_io), false)
272         );
273
274         match imp::Process::spawn(&self.inner, their_stdin, their_stdout,
275                                   their_stderr) {
276             Err(e) => Err(e),
277             Ok(handle) => Ok(Child {
278                 handle: handle,
279                 status: None,
280                 stdin: our_stdin.map(|fd| ChildStdin { inner: fd }),
281                 stdout: our_stdout.map(|fd| ChildStdout { inner: fd }),
282                 stderr: our_stderr.map(|fd| ChildStderr { inner: fd }),
283             })
284         }
285     }
286
287     /// Executes the command as a child process, returning a handle to it.
288     ///
289     /// By default, stdin, stdout and stderr are inherited from the parent.
290     #[stable(feature = "process", since = "1.0.0")]
291     pub fn spawn(&mut self) -> io::Result<Child> {
292         self.spawn_inner(StdioImp::Inherit)
293     }
294
295     /// Executes the command as a child process, waiting for it to finish and
296     /// collecting all of its output.
297     ///
298     /// By default, stdin, stdout and stderr are captured (and used to
299     /// provide the resulting output).
300     ///
301     /// # Examples
302     ///
303     /// ```
304     /// use std::process::Command;
305     /// let output = Command::new("cat").arg("foo.txt").output().unwrap_or_else(|e| {
306     ///     panic!("failed to execute process: {}", e)
307     /// });
308     ///
309     /// println!("status: {}", output.status);
310     /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
311     /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
312     /// ```
313     #[stable(feature = "process", since = "1.0.0")]
314     pub fn output(&mut self) -> io::Result<Output> {
315         self.spawn_inner(StdioImp::MakePipe).and_then(|p| p.wait_with_output())
316     }
317
318     /// Executes a command as a child process, waiting for it to finish and
319     /// collecting its exit status.
320     ///
321     /// By default, stdin, stdout and stderr are inherited from the parent.
322     ///
323     /// # Examples
324     ///
325     /// ```
326     /// use std::process::Command;
327     ///
328     /// let status = Command::new("ls").status().unwrap_or_else(|e| {
329     ///     panic!("failed to execute process: {}", e)
330     /// });
331     ///
332     /// println!("process exited with: {}", status);
333     /// ```
334     #[stable(feature = "process", since = "1.0.0")]
335     pub fn status(&mut self) -> io::Result<ExitStatus> {
336         self.spawn().and_then(|mut p| p.wait())
337     }
338 }
339
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl fmt::Debug for Command {
342     /// Format the program and arguments of a Command for display. Any
343     /// non-utf8 data is lossily converted using the utf8 replacement
344     /// character.
345     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
346         try!(write!(f, "{:?}", self.inner.program));
347         for arg in &self.inner.args {
348             try!(write!(f, " {:?}", arg));
349         }
350         Ok(())
351     }
352 }
353
354 impl AsInner<imp::Command> for Command {
355     fn as_inner(&self) -> &imp::Command { &self.inner }
356 }
357
358 impl AsInnerMut<imp::Command> for Command {
359     fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
360 }
361
362 // Takes a `Stdio` configuration (this module) and whether the to-be-owned
363 // handle will be readable.
364 //
365 // Returns a triple of (stdio to spawn with, stdio to store, stdio to drop). The
366 // stdio to spawn with is passed down to the `sys` module and indicates how the
367 // stdio stream should be set up. The "stdio to store" is an object which
368 // should be returned in the `Child` that makes its way out. The "stdio to drop"
369 // represents the raw value of "stdio to spawn with", but is the owned variant
370 // for it. This needs to be dropped after the child spawns
371 fn setup_io(io: &Stdio, readable: bool)
372             -> io::Result<(imp::Stdio, Option<AnonPipe>, Option<AnonPipe>)>
373 {
374     Ok(match io.0 {
375         StdioImp::MakePipe => {
376             let (reader, writer) = try!(pipe::anon_pipe());
377             if readable {
378                 (imp::Stdio::Raw(reader.raw()), Some(writer), Some(reader))
379             } else {
380                 (imp::Stdio::Raw(writer.raw()), Some(reader), Some(writer))
381             }
382         }
383         StdioImp::Raw(ref owned) => (imp::Stdio::Raw(owned.raw()), None, None),
384         StdioImp::Inherit => (imp::Stdio::Inherit, None, None),
385         StdioImp::None => (imp::Stdio::None, None, None),
386     })
387 }
388
389 /// The output of a finished process.
390 #[derive(PartialEq, Eq, Clone)]
391 #[stable(feature = "process", since = "1.0.0")]
392 pub struct Output {
393     /// The status (exit code) of the process.
394     #[stable(feature = "process", since = "1.0.0")]
395     pub status: ExitStatus,
396     /// The data that the process wrote to stdout.
397     #[stable(feature = "process", since = "1.0.0")]
398     pub stdout: Vec<u8>,
399     /// The data that the process wrote to stderr.
400     #[stable(feature = "process", since = "1.0.0")]
401     pub stderr: Vec<u8>,
402 }
403
404 /// Describes what to do with a standard I/O stream for a child process.
405 #[stable(feature = "process", since = "1.0.0")]
406 pub struct Stdio(StdioImp);
407
408 // The internal enum for stdio setup; see below for descriptions.
409 enum StdioImp {
410     MakePipe,
411     Raw(imp::RawStdio),
412     Inherit,
413     None,
414 }
415
416 impl Stdio {
417     /// A new pipe should be arranged to connect the parent and child processes.
418     #[stable(feature = "process", since = "1.0.0")]
419     pub fn piped() -> Stdio { Stdio(StdioImp::MakePipe) }
420
421     /// The child inherits from the corresponding parent descriptor.
422     #[stable(feature = "process", since = "1.0.0")]
423     pub fn inherit() -> Stdio { Stdio(StdioImp::Inherit) }
424
425     /// This stream will be ignored. This is the equivalent of attaching the
426     /// stream to `/dev/null`
427     #[stable(feature = "process", since = "1.0.0")]
428     pub fn null() -> Stdio { Stdio(StdioImp::None) }
429 }
430
431 impl FromInner<imp::RawStdio> for Stdio {
432     fn from_inner(inner: imp::RawStdio) -> Stdio {
433         Stdio(StdioImp::Raw(inner))
434     }
435 }
436
437 /// Describes the result of a process after it has terminated.
438 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
439 #[stable(feature = "process", since = "1.0.0")]
440 pub struct ExitStatus(imp::ExitStatus);
441
442 impl ExitStatus {
443     /// Was termination successful? Signal termination not considered a success,
444     /// and success is defined as a zero exit status.
445     #[stable(feature = "process", since = "1.0.0")]
446     pub fn success(&self) -> bool {
447         self.0.success()
448     }
449
450     /// Returns the exit code of the process, if any.
451     ///
452     /// On Unix, this will return `None` if the process was terminated
453     /// by a signal; `std::os::unix` provides an extension trait for
454     /// extracting the signal and other details from the `ExitStatus`.
455     #[stable(feature = "process", since = "1.0.0")]
456     pub fn code(&self) -> Option<i32> {
457         self.0.code()
458     }
459 }
460
461 impl AsInner<imp::ExitStatus> for ExitStatus {
462     fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
463 }
464
465 #[stable(feature = "process", since = "1.0.0")]
466 impl fmt::Display for ExitStatus {
467     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
468         self.0.fmt(f)
469     }
470 }
471
472 impl Child {
473     /// Forces the child to exit. This is equivalent to sending a
474     /// SIGKILL on unix platforms.
475     #[stable(feature = "process", since = "1.0.0")]
476     pub fn kill(&mut self) -> io::Result<()> {
477         #[cfg(unix)] fn collect_status(p: &mut Child) {
478             // On Linux (and possibly other unices), a process that has exited will
479             // continue to accept signals because it is "defunct". The delivery of
480             // signals will only fail once the child has been reaped. For this
481             // reason, if the process hasn't exited yet, then we attempt to collect
482             // their status with WNOHANG.
483             if p.status.is_none() {
484                 match p.handle.try_wait() {
485                     Some(status) => { p.status = Some(status); }
486                     None => {}
487                 }
488             }
489         }
490         #[cfg(windows)] fn collect_status(_p: &mut Child) {}
491
492         collect_status(self);
493
494         // if the process has finished, and therefore had waitpid called,
495         // and we kill it, then on unix we might ending up killing a
496         // newer process that happens to have the same (re-used) id
497         if self.status.is_some() {
498             return Err(Error::new(
499                 ErrorKind::InvalidInput,
500                 "invalid argument: can't kill an exited process",
501             ))
502         }
503
504         unsafe { self.handle.kill() }
505     }
506
507     /// Returns the OS-assigned process identifier associated with this child.
508     #[stable(feature = "process_id", since = "1.3.0")]
509     pub fn id(&self) -> u32 {
510         self.handle.id()
511     }
512
513     /// Waits for the child to exit completely, returning the status that it
514     /// exited with. This function will continue to have the same return value
515     /// after it has been called at least once.
516     ///
517     /// The stdin handle to the child process, if any, will be closed
518     /// before waiting. This helps avoid deadlock: it ensures that the
519     /// child does not block waiting for input from the parent, while
520     /// the parent waits for the child to exit.
521     #[stable(feature = "process", since = "1.0.0")]
522     pub fn wait(&mut self) -> io::Result<ExitStatus> {
523         drop(self.stdin.take());
524         match self.status {
525             Some(code) => Ok(ExitStatus(code)),
526             None => {
527                 let status = try!(self.handle.wait());
528                 self.status = Some(status);
529                 Ok(ExitStatus(status))
530             }
531         }
532     }
533
534     /// Simultaneously waits for the child to exit and collect all remaining
535     /// output on the stdout/stderr handles, returning a `Output`
536     /// instance.
537     ///
538     /// The stdin handle to the child process, if any, will be closed
539     /// before waiting. This helps avoid deadlock: it ensures that the
540     /// child does not block waiting for input from the parent, while
541     /// the parent waits for the child to exit.
542     #[stable(feature = "process", since = "1.0.0")]
543     pub fn wait_with_output(mut self) -> io::Result<Output> {
544         drop(self.stdin.take());
545         fn read<T: Read + Send + 'static>(stream: Option<T>) -> Receiver<io::Result<Vec<u8>>> {
546             let (tx, rx) = channel();
547             match stream {
548                 Some(stream) => {
549                     thread::spawn(move || {
550                         let mut stream = stream;
551                         let mut ret = Vec::new();
552                         let res = stream.read_to_end(&mut ret);
553                         tx.send(res.map(|_| ret)).unwrap();
554                     });
555                 }
556                 None => tx.send(Ok(Vec::new())).unwrap()
557             }
558             rx
559         }
560         let stdout = read(self.stdout.take());
561         let stderr = read(self.stderr.take());
562         let status = try!(self.wait());
563
564         Ok(Output {
565             status: status,
566             stdout: stdout.recv().unwrap().unwrap_or(Vec::new()),
567             stderr:  stderr.recv().unwrap().unwrap_or(Vec::new()),
568         })
569     }
570 }
571
572 /// Terminates the current process with the specified exit code.
573 ///
574 /// This function will never return and will immediately terminate the current
575 /// process. The exit code is passed through to the underlying OS and will be
576 /// available for consumption by another process.
577 ///
578 /// Note that because this function never returns, and that it terminates the
579 /// process, no destructors on the current stack or any other thread's stack
580 /// will be run. If a clean shutdown is needed it is recommended to only call
581 /// this function at a known point where there are no more destructors left
582 /// to run.
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn exit(code: i32) -> ! {
585     ::sys_common::cleanup();
586     ::sys::os::exit(code)
587 }
588
589 #[cfg(test)]
590 mod tests {
591     use prelude::v1::*;
592     use io::prelude::*;
593
594     use io::ErrorKind;
595     use str;
596     use super::{Command, Output, Stdio};
597
598     // FIXME(#10380) these tests should not all be ignored on android.
599
600     #[cfg(not(target_os="android"))]
601     #[test]
602     fn smoke() {
603         let p = Command::new("true").spawn();
604         assert!(p.is_ok());
605         let mut p = p.unwrap();
606         assert!(p.wait().unwrap().success());
607     }
608
609     #[cfg(not(target_os="android"))]
610     #[test]
611     fn smoke_failure() {
612         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
613             Ok(..) => panic!(),
614             Err(..) => {}
615         }
616     }
617
618     #[cfg(not(target_os="android"))]
619     #[test]
620     fn exit_reported_right() {
621         let p = Command::new("false").spawn();
622         assert!(p.is_ok());
623         let mut p = p.unwrap();
624         assert!(p.wait().unwrap().code() == Some(1));
625         drop(p.wait());
626     }
627
628     #[cfg(all(unix, not(target_os="android")))]
629     #[test]
630     fn signal_reported_right() {
631         use os::unix::process::ExitStatusExt;
632
633         let mut p = Command::new("/bin/sh")
634                             .arg("-c").arg("read a")
635                             .stdin(Stdio::piped())
636                             .spawn().unwrap();
637         p.kill().unwrap();
638         match p.wait().unwrap().signal() {
639             Some(9) => {},
640             result => panic!("not terminated by signal 9 (instead, {:?})",
641                              result),
642         }
643     }
644
645     pub fn run_output(mut cmd: Command) -> String {
646         let p = cmd.spawn();
647         assert!(p.is_ok());
648         let mut p = p.unwrap();
649         assert!(p.stdout.is_some());
650         let mut ret = String::new();
651         p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
652         assert!(p.wait().unwrap().success());
653         return ret;
654     }
655
656     #[cfg(not(target_os="android"))]
657     #[test]
658     fn stdout_works() {
659         let mut cmd = Command::new("echo");
660         cmd.arg("foobar").stdout(Stdio::piped());
661         assert_eq!(run_output(cmd), "foobar\n");
662     }
663
664     #[cfg(all(unix, not(target_os="android")))]
665     #[test]
666     fn set_current_dir_works() {
667         let mut cmd = Command::new("/bin/sh");
668         cmd.arg("-c").arg("pwd")
669            .current_dir("/")
670            .stdout(Stdio::piped());
671         assert_eq!(run_output(cmd), "/\n");
672     }
673
674     #[cfg(all(unix, not(target_os="android")))]
675     #[test]
676     fn stdin_works() {
677         let mut p = Command::new("/bin/sh")
678                             .arg("-c").arg("read line; echo $line")
679                             .stdin(Stdio::piped())
680                             .stdout(Stdio::piped())
681                             .spawn().unwrap();
682         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
683         drop(p.stdin.take());
684         let mut out = String::new();
685         p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
686         assert!(p.wait().unwrap().success());
687         assert_eq!(out, "foobar\n");
688     }
689
690
691     #[cfg(all(unix, not(target_os="android")))]
692     #[test]
693     fn uid_works() {
694         use os::unix::prelude::*;
695         use libc;
696         let mut p = Command::new("/bin/sh")
697                             .arg("-c").arg("true")
698                             .uid(unsafe { libc::getuid() })
699                             .gid(unsafe { libc::getgid() })
700                             .spawn().unwrap();
701         assert!(p.wait().unwrap().success());
702     }
703
704     #[cfg(all(unix, not(target_os="android")))]
705     #[test]
706     fn uid_to_root_fails() {
707         use os::unix::prelude::*;
708         use libc;
709
710         // if we're already root, this isn't a valid test. Most of the bots run
711         // as non-root though (android is an exception).
712         if unsafe { libc::getuid() == 0 } { return }
713         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
714     }
715
716     #[cfg(not(target_os="android"))]
717     #[test]
718     fn test_process_status() {
719         let mut status = Command::new("false").status().unwrap();
720         assert!(status.code() == Some(1));
721
722         status = Command::new("true").status().unwrap();
723         assert!(status.success());
724     }
725
726     #[test]
727     fn test_process_output_fail_to_start() {
728         match Command::new("/no-binary-by-this-name-should-exist").output() {
729             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
730             Ok(..) => panic!()
731         }
732     }
733
734     #[cfg(not(target_os="android"))]
735     #[test]
736     fn test_process_output_output() {
737         let Output {status, stdout, stderr}
738              = Command::new("echo").arg("hello").output().unwrap();
739         let output_str = str::from_utf8(&stdout).unwrap();
740
741         assert!(status.success());
742         assert_eq!(output_str.trim().to_string(), "hello");
743         assert_eq!(stderr, Vec::new());
744     }
745
746     #[cfg(not(target_os="android"))]
747     #[test]
748     fn test_process_output_error() {
749         let Output {status, stdout, stderr}
750              = Command::new("mkdir").arg(".").output().unwrap();
751
752         assert!(status.code() == Some(1));
753         assert_eq!(stdout, Vec::new());
754         assert!(!stderr.is_empty());
755     }
756
757     #[cfg(not(target_os="android"))]
758     #[test]
759     fn test_finish_once() {
760         let mut prog = Command::new("false").spawn().unwrap();
761         assert!(prog.wait().unwrap().code() == Some(1));
762     }
763
764     #[cfg(not(target_os="android"))]
765     #[test]
766     fn test_finish_twice() {
767         let mut prog = Command::new("false").spawn().unwrap();
768         assert!(prog.wait().unwrap().code() == Some(1));
769         assert!(prog.wait().unwrap().code() == Some(1));
770     }
771
772     #[cfg(not(target_os="android"))]
773     #[test]
774     fn test_wait_with_output_once() {
775         let prog = Command::new("echo").arg("hello").stdout(Stdio::piped())
776             .spawn().unwrap();
777         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
778         let output_str = str::from_utf8(&stdout).unwrap();
779
780         assert!(status.success());
781         assert_eq!(output_str.trim().to_string(), "hello");
782         assert_eq!(stderr, Vec::new());
783     }
784
785     #[cfg(all(unix, not(target_os="android")))]
786     pub fn env_cmd() -> Command {
787         Command::new("env")
788     }
789     #[cfg(target_os="android")]
790     pub fn env_cmd() -> Command {
791         let mut cmd = Command::new("/system/bin/sh");
792         cmd.arg("-c").arg("set");
793         cmd
794     }
795
796     #[cfg(windows)]
797     pub fn env_cmd() -> Command {
798         let mut cmd = Command::new("cmd");
799         cmd.arg("/c").arg("set");
800         cmd
801     }
802
803     #[cfg(not(target_os="android"))]
804     #[test]
805     fn test_inherit_env() {
806         use env;
807
808         let result = env_cmd().output().unwrap();
809         let output = String::from_utf8(result.stdout).unwrap();
810
811         for (ref k, ref v) in env::vars() {
812             // don't check windows magical empty-named variables
813             assert!(k.is_empty() ||
814                     output.contains(&format!("{}={}", *k, *v)),
815                     "output doesn't contain `{}={}`\n{}",
816                     k, v, output);
817         }
818     }
819     #[cfg(target_os="android")]
820     #[test]
821     fn test_inherit_env() {
822         use env;
823
824         let mut result = env_cmd().output().unwrap();
825         let output = String::from_utf8(result.stdout).unwrap();
826
827         for (ref k, ref v) in env::vars() {
828             // don't check android RANDOM variables
829             if *k != "RANDOM".to_string() {
830                 assert!(output.contains(&format!("{}={}",
831                                                  *k,
832                                                  *v)) ||
833                         output.contains(&format!("{}=\'{}\'",
834                                                  *k,
835                                                  *v)));
836             }
837         }
838     }
839
840     #[test]
841     fn test_override_env() {
842         use env;
843
844         // In some build environments (such as chrooted Nix builds), `env` can
845         // only be found in the explicitly-provided PATH env variable, not in
846         // default places such as /bin or /usr/bin. So we need to pass through
847         // PATH to our sub-process.
848         let mut cmd = env_cmd();
849         cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
850         if let Some(p) = env::var_os("PATH") {
851             cmd.env("PATH", &p);
852         }
853         let result = cmd.output().unwrap();
854         let output = String::from_utf8_lossy(&result.stdout).to_string();
855
856         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
857                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
858     }
859
860     #[test]
861     fn test_add_to_env() {
862         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
863         let output = String::from_utf8_lossy(&result.stdout).to_string();
864
865         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
866                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
867     }
868 }