]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/process.rs
7b0a86777f6923d783a9bb3475ecb500f61ab554
[rust.git] / src / libstd / io / process.rs
1 // Copyright 2013 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 //! Bindings for executing child processes
12
13 #![allow(unstable)]
14 #![allow(non_upper_case_globals)]
15
16 pub use self::StdioContainer::*;
17 pub use self::ProcessExit::*;
18
19 use prelude::v1::*;
20
21 use collections::HashMap;
22 use ffi::CString;
23 use fmt;
24 // NOTE(stage0) remove import after a snapshot
25 #[cfg(stage0)]
26 use hash::Hash;
27 use io::pipe::{PipeStream, PipePair};
28 use io::{IoResult, IoError};
29 use io;
30 use libc;
31 use os;
32 use path::BytesContainer;
33 use sync::mpsc::{channel, Receiver};
34 use sys::fs::FileDesc;
35 use sys::process::Process as ProcessImp;
36 use sys;
37 use thread::Thread;
38
39 #[cfg(windows)] use hash;
40 #[cfg(windows)] use str;
41
42 /// Signal a process to exit, without forcibly killing it. Corresponds to
43 /// SIGTERM on unix platforms.
44 #[cfg(windows)] pub const PleaseExitSignal: int = 15;
45 /// Signal a process to exit immediately, forcibly killing it. Corresponds to
46 /// SIGKILL on unix platforms.
47 #[cfg(windows)] pub const MustDieSignal: int = 9;
48 /// Signal a process to exit, without forcibly killing it. Corresponds to
49 /// SIGTERM on unix platforms.
50 #[cfg(not(windows))] pub const PleaseExitSignal: int = libc::SIGTERM as int;
51 /// Signal a process to exit immediately, forcibly killing it. Corresponds to
52 /// SIGKILL on unix platforms.
53 #[cfg(not(windows))] pub const MustDieSignal: int = libc::SIGKILL as int;
54
55 /// Representation of a running or exited child process.
56 ///
57 /// This structure is used to represent and manage child processes. A child
58 /// process is created via the `Command` struct, which configures the spawning
59 /// process and can itself be constructed using a builder-style interface.
60 ///
61 /// # Example
62 ///
63 /// ```should_fail
64 /// use std::io::Command;
65 ///
66 /// let mut child = match Command::new("/bin/cat").arg("file.txt").spawn() {
67 ///     Ok(child) => child,
68 ///     Err(e) => panic!("failed to execute child: {}", e),
69 /// };
70 ///
71 /// let contents = child.stdout.as_mut().unwrap().read_to_end();
72 /// assert!(child.wait().unwrap().success());
73 /// ```
74 pub struct Process {
75     handle: ProcessImp,
76     forget: bool,
77
78     /// None until wait() is called.
79     exit_code: Option<ProcessExit>,
80
81     /// Manually delivered signal
82     exit_signal: Option<int>,
83
84     /// Deadline after which wait() will return
85     deadline: u64,
86
87     /// Handle to the child's stdin, if the `stdin` field of this process's
88     /// `ProcessConfig` was `CreatePipe`. By default, this handle is `Some`.
89     pub stdin: Option<PipeStream>,
90
91     /// Handle to the child's stdout, if the `stdout` field of this process's
92     /// `ProcessConfig` was `CreatePipe`. By default, this handle is `Some`.
93     pub stdout: Option<PipeStream>,
94
95     /// Handle to the child's stderr, if the `stderr` field of this process's
96     /// `ProcessConfig` was `CreatePipe`. By default, this handle is `Some`.
97     pub stderr: Option<PipeStream>,
98 }
99
100 /// A representation of environment variable name
101 /// It compares case-insensitive on Windows and case-sensitive everywhere else.
102 #[cfg(not(windows))]
103 #[derive(Hash, PartialEq, Eq, Clone, Show)]
104 struct EnvKey(CString);
105
106 #[doc(hidden)]
107 #[cfg(windows)]
108 #[derive(Eq, Clone, Show)]
109 struct EnvKey(CString);
110
111 #[cfg(windows)]
112 impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for EnvKey {
113     fn hash(&self, state: &mut H) {
114         let &EnvKey(ref x) = self;
115         match str::from_utf8(x.as_bytes()) {
116             Ok(s) => for ch in s.chars() {
117                 (ch as u8 as char).to_lowercase().hash(state);
118             },
119             Err(..) => x.hash(state)
120         }
121     }
122 }
123
124 #[cfg(windows)]
125 impl PartialEq for EnvKey {
126     fn eq(&self, other: &EnvKey) -> bool {
127         let &EnvKey(ref x) = self;
128         let &EnvKey(ref y) = other;
129         match (str::from_utf8(x.as_bytes()), str::from_utf8(y.as_bytes())) {
130             (Ok(xs), Ok(ys)) => {
131                 if xs.len() != ys.len() {
132                     return false
133                 } else {
134                     for (xch, ych) in xs.chars().zip(ys.chars()) {
135                         if xch.to_lowercase() != ych.to_lowercase() {
136                             return false;
137                         }
138                     }
139                     return true;
140                 }
141             },
142             // If either is not a valid utf8 string, just compare them byte-wise
143             _ => return x.eq(y)
144         }
145     }
146 }
147
148 impl BytesContainer for EnvKey {
149     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
150         let &EnvKey(ref k) = self;
151         k.container_as_bytes()
152     }
153 }
154
155 /// A HashMap representation of environment variables.
156 pub type EnvMap = HashMap<EnvKey, CString>;
157
158 /// The `Command` type acts as a process builder, providing fine-grained control
159 /// over how a new process should be spawned. A default configuration can be
160 /// generated using `Command::new(program)`, where `program` gives a path to the
161 /// program to be executed. Additional builder methods allow the configuration
162 /// to be changed (for example, by adding arguments) prior to spawning:
163 ///
164 /// ```
165 /// use std::io::Command;
166 ///
167 /// let mut process = match Command::new("sh").arg("-c").arg("echo hello").spawn() {
168 ///   Ok(p) => p,
169 ///   Err(e) => panic!("failed to execute process: {}", e),
170 /// };
171 ///
172 /// let output = process.stdout.as_mut().unwrap().read_to_end();
173 /// ```
174 #[derive(Clone)]
175 pub struct Command {
176     // The internal data for the builder. Documented by the builder
177     // methods below, and serialized into rt::rtio::ProcessConfig.
178     program: CString,
179     args: Vec<CString>,
180     env: Option<EnvMap>,
181     cwd: Option<CString>,
182     stdin: StdioContainer,
183     stdout: StdioContainer,
184     stderr: StdioContainer,
185     uid: Option<uint>,
186     gid: Option<uint>,
187     detach: bool,
188 }
189
190 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
191 // we cannot usefully take BytesContainer arguments by reference (without forcing an
192 // additional & around &str). So we are instead temporarily adding an instance
193 // for &Path, so that we can take BytesContainer as owned. When DST lands, the &Path
194 // instance should be removed, and arguments bound by BytesContainer should be passed by
195 // reference. (Here: {new, arg, args, env}.)
196
197 impl Command {
198     /// Constructs a new `Command` for launching the program at
199     /// path `program`, with the following default configuration:
200     ///
201     /// * No arguments to the program
202     /// * Inherit the current process's environment
203     /// * Inherit the current process's working directory
204     /// * A readable pipe for stdin (file descriptor 0)
205     /// * A writeable pipe for stdout and stderr (file descriptors 1 and 2)
206     ///
207     /// Builder methods are provided to change these defaults and
208     /// otherwise configure the process.
209     pub fn new<T: BytesContainer>(program: T) -> Command {
210         Command {
211             program: CString::from_slice(program.container_as_bytes()),
212             args: Vec::new(),
213             env: None,
214             cwd: None,
215             stdin: CreatePipe(true, false),
216             stdout: CreatePipe(false, true),
217             stderr: CreatePipe(false, true),
218             uid: None,
219             gid: None,
220             detach: false,
221         }
222     }
223
224     /// Add an argument to pass to the program.
225     pub fn arg<'a, T: BytesContainer>(&'a mut self, arg: T) -> &'a mut Command {
226         self.args.push(CString::from_slice(arg.container_as_bytes()));
227         self
228     }
229
230     /// Add multiple arguments to pass to the program.
231     pub fn args<'a, T: BytesContainer>(&'a mut self, args: &[T]) -> &'a mut Command {
232         self.args.extend(args.iter().map(|arg| {
233             CString::from_slice(arg.container_as_bytes())
234         }));
235         self
236     }
237     // Get a mutable borrow of the environment variable map for this `Command`.
238     fn get_env_map<'a>(&'a mut self) -> &'a mut EnvMap {
239         match self.env {
240             Some(ref mut map) => map,
241             None => {
242                 // if the env is currently just inheriting from the parent's,
243                 // materialize the parent's env into a hashtable.
244                 self.env = Some(os::env_as_bytes().into_iter().map(|(k, v)| {
245                     (EnvKey(CString::from_slice(k.as_slice())),
246                      CString::from_slice(v.as_slice()))
247                 }).collect());
248                 self.env.as_mut().unwrap()
249             }
250         }
251     }
252
253     /// Inserts or updates an environment variable mapping.
254     ///
255     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
256     /// and case-sensitive on all other platforms.
257     pub fn env<'a, T, U>(&'a mut self, key: T, val: U)
258                          -> &'a mut Command
259                          where T: BytesContainer, U: BytesContainer {
260         let key = EnvKey(CString::from_slice(key.container_as_bytes()));
261         let val = CString::from_slice(val.container_as_bytes());
262         self.get_env_map().insert(key, val);
263         self
264     }
265
266     /// Removes an environment variable mapping.
267     pub fn env_remove<'a, T>(&'a mut self, key: T) -> &'a mut Command
268                              where T: BytesContainer {
269         let key = EnvKey(CString::from_slice(key.container_as_bytes()));
270         self.get_env_map().remove(&key);
271         self
272     }
273
274     /// Sets the entire environment map for the child process.
275     ///
276     /// If the given slice contains multiple instances of an environment
277     /// variable, the *rightmost* instance will determine the value.
278     pub fn env_set_all<'a, T, U>(&'a mut self, env: &[(T,U)])
279                                  -> &'a mut Command
280                                  where T: BytesContainer, U: BytesContainer {
281         self.env = Some(env.iter().map(|&(ref k, ref v)| {
282             (EnvKey(CString::from_slice(k.container_as_bytes())),
283              CString::from_slice(v.container_as_bytes()))
284         }).collect());
285         self
286     }
287
288     /// Set the working directory for the child process.
289     pub fn cwd<'a>(&'a mut self, dir: &Path) -> &'a mut Command {
290         self.cwd = Some(CString::from_slice(dir.as_vec()));
291         self
292     }
293
294     /// Configuration for the child process's stdin handle (file descriptor 0).
295     /// Defaults to `CreatePipe(true, false)` so the input can be written to.
296     pub fn stdin<'a>(&'a mut self, cfg: StdioContainer) -> &'a mut Command {
297         self.stdin = cfg;
298         self
299     }
300
301     /// Configuration for the child process's stdout handle (file descriptor 1).
302     /// Defaults to `CreatePipe(false, true)` so the output can be collected.
303     pub fn stdout<'a>(&'a mut self, cfg: StdioContainer) -> &'a mut Command {
304         self.stdout = cfg;
305         self
306     }
307
308     /// Configuration for the child process's stderr handle (file descriptor 2).
309     /// Defaults to `CreatePipe(false, true)` so the output can be collected.
310     pub fn stderr<'a>(&'a mut self, cfg: StdioContainer) -> &'a mut Command {
311         self.stderr = cfg;
312         self
313     }
314
315     /// Sets the child process's user id. This translates to a `setuid` call in
316     /// the child process. Setting this value on windows will cause the spawn to
317     /// fail. Failure in the `setuid` call on unix will also cause the spawn to
318     /// fail.
319     pub fn uid<'a>(&'a mut self, id: uint) -> &'a mut Command {
320         self.uid = Some(id);
321         self
322     }
323
324     /// Similar to `uid`, but sets the group id of the child process. This has
325     /// the same semantics as the `uid` field.
326     pub fn gid<'a>(&'a mut self, id: uint) -> &'a mut Command {
327         self.gid = Some(id);
328         self
329     }
330
331     /// Sets the child process to be spawned in a detached state. On unix, this
332     /// means that the child is the leader of a new process group.
333     pub fn detached<'a>(&'a mut self) -> &'a mut Command {
334         self.detach = true;
335         self
336     }
337
338     /// Executes the command as a child process, which is returned.
339     pub fn spawn(&self) -> IoResult<Process> {
340         let (their_stdin, our_stdin) = try!(setup_io(self.stdin));
341         let (their_stdout, our_stdout) = try!(setup_io(self.stdout));
342         let (their_stderr, our_stderr) = try!(setup_io(self.stderr));
343
344         match ProcessImp::spawn(self, their_stdin, their_stdout, their_stderr) {
345             Err(e) => Err(e),
346             Ok(handle) => Ok(Process {
347                 handle: handle,
348                 forget: false,
349                 exit_code: None,
350                 exit_signal: None,
351                 deadline: 0,
352                 stdin: our_stdin,
353                 stdout: our_stdout,
354                 stderr: our_stderr,
355             })
356         }
357     }
358
359     /// Executes the command as a child process, waiting for it to finish and
360     /// collecting all of its output.
361     ///
362     /// # Example
363     ///
364     /// ```
365     /// use std::io::Command;
366     ///
367     /// let output = match Command::new("cat").arg("foot.txt").output() {
368     ///     Ok(output) => output,
369     ///     Err(e) => panic!("failed to execute process: {}", e),
370     /// };
371     ///
372     /// println!("status: {}", output.status);
373     /// println!("stdout: {}", String::from_utf8_lossy(output.output.as_slice()));
374     /// println!("stderr: {}", String::from_utf8_lossy(output.error.as_slice()));
375     /// ```
376     pub fn output(&self) -> IoResult<ProcessOutput> {
377         self.spawn().and_then(|p| p.wait_with_output())
378     }
379
380     /// Executes a command as a child process, waiting for it to finish and
381     /// collecting its exit status.
382     ///
383     /// # Example
384     ///
385     /// ```
386     /// use std::io::Command;
387     ///
388     /// let status = match Command::new("ls").status() {
389     ///     Ok(status) => status,
390     ///     Err(e) => panic!("failed to execute process: {}", e),
391     /// };
392     ///
393     /// println!("process exited with: {}", status);
394     /// ```
395     pub fn status(&self) -> IoResult<ProcessExit> {
396         self.spawn().and_then(|mut p| p.wait())
397     }
398 }
399
400 impl fmt::Debug for Command {
401     /// Format the program and arguments of a Command for display. Any
402     /// non-utf8 data is lossily converted using the utf8 replacement
403     /// character.
404     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
405         try!(write!(f, "{}", String::from_utf8_lossy(self.program.as_bytes())));
406         for arg in self.args.iter() {
407             try!(write!(f, " '{}'", String::from_utf8_lossy(arg.as_bytes())));
408         }
409         Ok(())
410     }
411 }
412
413 fn setup_io(io: StdioContainer) -> IoResult<(Option<PipeStream>, Option<PipeStream>)> {
414     let ours;
415     let theirs;
416     match io {
417         Ignored => {
418             theirs = None;
419             ours = None;
420         }
421         InheritFd(fd) => {
422             theirs = Some(PipeStream::from_filedesc(FileDesc::new(fd, false)));
423             ours = None;
424         }
425         CreatePipe(readable, _writable) => {
426             let PipePair { reader, writer } = try!(PipeStream::pair());
427             if readable {
428                 theirs = Some(reader);
429                 ours = Some(writer);
430             } else {
431                 theirs = Some(writer);
432                 ours = Some(reader);
433             }
434         }
435     }
436     Ok((theirs, ours))
437 }
438
439 // Allow the sys module to get access to the Command state
440 impl sys::process::ProcessConfig<EnvKey, CString> for Command {
441     fn program(&self) -> &CString {
442         &self.program
443     }
444     fn args(&self) -> &[CString] {
445         self.args.as_slice()
446     }
447     fn env(&self) -> Option<&EnvMap> {
448         self.env.as_ref()
449     }
450     fn cwd(&self) -> Option<&CString> {
451         self.cwd.as_ref()
452     }
453     fn uid(&self) -> Option<uint> {
454         self.uid.clone()
455     }
456     fn gid(&self) -> Option<uint> {
457         self.gid.clone()
458     }
459     fn detach(&self) -> bool {
460         self.detach
461     }
462
463 }
464
465 /// The output of a finished process.
466 #[derive(PartialEq, Eq, Clone)]
467 pub struct ProcessOutput {
468     /// The status (exit code) of the process.
469     pub status: ProcessExit,
470     /// The data that the process wrote to stdout.
471     pub output: Vec<u8>,
472     /// The data that the process wrote to stderr.
473     pub error: Vec<u8>,
474 }
475
476 /// Describes what to do with a standard io stream for a child process.
477 #[derive(Clone, Copy)]
478 pub enum StdioContainer {
479     /// This stream will be ignored. This is the equivalent of attaching the
480     /// stream to `/dev/null`
481     Ignored,
482
483     /// The specified file descriptor is inherited for the stream which it is
484     /// specified for. Ownership of the file descriptor is *not* taken, so the
485     /// caller must clean it up.
486     InheritFd(libc::c_int),
487
488     /// Creates a pipe for the specified file descriptor which will be created
489     /// when the process is spawned.
490     ///
491     /// The first boolean argument is whether the pipe is readable, and the
492     /// second is whether it is writable. These properties are from the view of
493     /// the *child* process, not the parent process.
494     CreatePipe(bool /* readable */, bool /* writable */),
495 }
496
497 /// Describes the result of a process after it has terminated.
498 /// Note that Windows have no signals, so the result is usually ExitStatus.
499 #[derive(PartialEq, Eq, Clone, Copy, Show)]
500 pub enum ProcessExit {
501     /// Normal termination with an exit status.
502     ExitStatus(int),
503
504     /// Termination by signal, with the signal number.
505     ExitSignal(int),
506 }
507
508 #[stable]
509 impl fmt::Display for ProcessExit {
510     /// Format a ProcessExit enum, to nicely present the information.
511     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512         match *self {
513             ExitStatus(code) =>  write!(f, "exit code: {}", code),
514             ExitSignal(code) =>  write!(f, "signal: {}", code),
515         }
516     }
517 }
518
519 impl ProcessExit {
520     /// Was termination successful? Signal termination not considered a success,
521     /// and success is defined as a zero exit status.
522     pub fn success(&self) -> bool {
523         return self.matches_exit_status(0);
524     }
525
526     /// Checks whether this ProcessExit matches the given exit status.
527     /// Termination by signal will never match an exit code.
528     pub fn matches_exit_status(&self, wanted: int) -> bool {
529         *self == ExitStatus(wanted)
530     }
531 }
532
533 impl Process {
534     /// Sends `signal` to another process in the system identified by `id`.
535     ///
536     /// Note that windows doesn't quite have the same model as unix, so some
537     /// unix signals are mapped to windows signals. Notably, unix termination
538     /// signals (SIGTERM/SIGKILL/SIGINT) are translated to `TerminateProcess`.
539     ///
540     /// Additionally, a signal number of 0 can check for existence of the target
541     /// process. Note, though, that on some platforms signals will continue to
542     /// be successfully delivered if the child has exited, but not yet been
543     /// reaped.
544     pub fn kill(id: libc::pid_t, signal: int) -> IoResult<()> {
545         unsafe { ProcessImp::killpid(id, signal) }
546     }
547
548     /// Returns the process id of this child process
549     pub fn id(&self) -> libc::pid_t { self.handle.id() }
550
551     /// Sends the specified signal to the child process, returning whether the
552     /// signal could be delivered or not.
553     ///
554     /// Note that signal 0 is interpreted as a poll to check whether the child
555     /// process is still alive or not. If an error is returned, then the child
556     /// process has exited.
557     ///
558     /// On some unix platforms signals will continue to be received after a
559     /// child has exited but not yet been reaped. In order to report the status
560     /// of signal delivery correctly, unix implementations may invoke
561     /// `waitpid()` with `WNOHANG` in order to reap the child as necessary.
562     ///
563     /// # Errors
564     ///
565     /// If the signal delivery fails, the corresponding error is returned.
566     pub fn signal(&mut self, signal: int) -> IoResult<()> {
567         #[cfg(unix)] fn collect_status(p: &mut Process) {
568             // On Linux (and possibly other unices), a process that has exited will
569             // continue to accept signals because it is "defunct". The delivery of
570             // signals will only fail once the child has been reaped. For this
571             // reason, if the process hasn't exited yet, then we attempt to collect
572             // their status with WNOHANG.
573             if p.exit_code.is_none() {
574                 match p.handle.try_wait() {
575                     Some(code) => { p.exit_code = Some(code); }
576                     None => {}
577                 }
578             }
579         }
580         #[cfg(windows)] fn collect_status(_p: &mut Process) {}
581
582         collect_status(self);
583
584         // if the process has finished, and therefore had waitpid called,
585         // and we kill it, then on unix we might ending up killing a
586         // newer process that happens to have the same (re-used) id
587         if self.exit_code.is_some() {
588             return Err(IoError {
589                 kind: io::InvalidInput,
590                 desc: "invalid argument: can't kill an exited process",
591                 detail: None,
592             })
593         }
594
595         // A successfully delivered signal that isn't 0 (just a poll for being
596         // alive) is recorded for windows (see wait())
597         match unsafe { self.handle.kill(signal) } {
598             Ok(()) if signal == 0 => Ok(()),
599             Ok(()) => { self.exit_signal = Some(signal); Ok(()) }
600             Err(e) => Err(e),
601         }
602
603     }
604
605     /// Sends a signal to this child requesting that it exits. This is
606     /// equivalent to sending a SIGTERM on unix platforms.
607     pub fn signal_exit(&mut self) -> IoResult<()> {
608         self.signal(PleaseExitSignal)
609     }
610
611     /// Sends a signal to this child forcing it to exit. This is equivalent to
612     /// sending a SIGKILL on unix platforms.
613     pub fn signal_kill(&mut self) -> IoResult<()> {
614         self.signal(MustDieSignal)
615     }
616
617     /// Wait for the child to exit completely, returning the status that it
618     /// exited with. This function will continue to have the same return value
619     /// after it has been called at least once.
620     ///
621     /// The stdin handle to the child process will be closed before waiting.
622     ///
623     /// # Errors
624     ///
625     /// This function can fail if a timeout was previously specified via
626     /// `set_timeout` and the timeout expires before the child exits.
627     pub fn wait(&mut self) -> IoResult<ProcessExit> {
628         drop(self.stdin.take());
629         match self.exit_code {
630             Some(code) => Ok(code),
631             None => {
632                 let code = try!(self.handle.wait(self.deadline));
633                 // On windows, waitpid will never return a signal. If a signal
634                 // was successfully delivered to the process, however, we can
635                 // consider it as having died via a signal.
636                 let code = match self.exit_signal {
637                     None => code,
638                     Some(signal) if cfg!(windows) => ExitSignal(signal),
639                     Some(..) => code,
640                 };
641                 self.exit_code = Some(code);
642                 Ok(code)
643             }
644         }
645     }
646
647     /// Sets a timeout, in milliseconds, for future calls to wait().
648     ///
649     /// The argument specified is a relative distance into the future, in
650     /// milliseconds, after which any call to wait() will return immediately
651     /// with a timeout error, and all future calls to wait() will not block.
652     ///
653     /// A value of `None` will clear any previous timeout, and a value of `Some`
654     /// will override any previously set timeout.
655     ///
656     /// # Example
657     ///
658     /// ```no_run
659     /// # #![allow(unstable)]
660     /// use std::io::{Command, IoResult};
661     /// use std::io::process::ProcessExit;
662     ///
663     /// fn run_gracefully(prog: &str) -> IoResult<ProcessExit> {
664     ///     let mut p = try!(Command::new("long-running-process").spawn());
665     ///
666     ///     // give the process 10 seconds to finish completely
667     ///     p.set_timeout(Some(10_000));
668     ///     match p.wait() {
669     ///         Ok(status) => return Ok(status),
670     ///         Err(..) => {}
671     ///     }
672     ///
673     ///     // Attempt to exit gracefully, but don't wait for it too long
674     ///     try!(p.signal_exit());
675     ///     p.set_timeout(Some(1_000));
676     ///     match p.wait() {
677     ///         Ok(status) => return Ok(status),
678     ///         Err(..) => {}
679     ///     }
680     ///
681     ///     // Well, we did our best, forcefully kill the process
682     ///     try!(p.signal_kill());
683     ///     p.set_timeout(None);
684     ///     p.wait()
685     /// }
686     /// ```
687     #[unstable = "the type of the timeout is likely to change"]
688     pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
689         self.deadline = timeout_ms.map(|i| i + sys::timer::now()).unwrap_or(0);
690     }
691
692     /// Simultaneously wait for the child to exit and collect all remaining
693     /// output on the stdout/stderr handles, returning a `ProcessOutput`
694     /// instance.
695     ///
696     /// The stdin handle to the child is closed before waiting.
697     ///
698     /// # Errors
699     ///
700     /// This function can fail for any of the same reasons that `wait()` can
701     /// fail.
702     pub fn wait_with_output(mut self) -> IoResult<ProcessOutput> {
703         drop(self.stdin.take());
704         fn read(stream: Option<io::PipeStream>) -> Receiver<IoResult<Vec<u8>>> {
705             let (tx, rx) = channel();
706             match stream {
707                 Some(stream) => {
708                     Thread::spawn(move |:| {
709                         let mut stream = stream;
710                         tx.send(stream.read_to_end()).unwrap();
711                     });
712                 }
713                 None => tx.send(Ok(Vec::new())).unwrap()
714             }
715             rx
716         }
717         let stdout = read(self.stdout.take());
718         let stderr = read(self.stderr.take());
719
720         let status = try!(self.wait());
721
722         Ok(ProcessOutput {
723             status: status,
724             output: stdout.recv().unwrap().unwrap_or(Vec::new()),
725             error:  stderr.recv().unwrap().unwrap_or(Vec::new()),
726         })
727     }
728
729     /// Forgets this process, allowing it to outlive the parent
730     ///
731     /// This function will forcefully prevent calling `wait()` on the child
732     /// process in the destructor, allowing the child to outlive the
733     /// parent. Note that this operation can easily lead to leaking the
734     /// resources of the child process, so care must be taken when
735     /// invoking this method.
736     pub fn forget(mut self) {
737         self.forget = true;
738     }
739 }
740
741 impl Drop for Process {
742     fn drop(&mut self) {
743         if self.forget { return }
744
745         // Close all I/O before exiting to ensure that the child doesn't wait
746         // forever to print some text or something similar.
747         drop(self.stdin.take());
748         drop(self.stdout.take());
749         drop(self.stderr.take());
750
751         self.set_timeout(None);
752         let _ = self.wait().unwrap();
753     }
754 }
755
756 #[cfg(test)]
757 mod tests {
758     use io::{Truncate, Write, TimedOut, timer, process, FileNotFound};
759     use prelude::v1::{Ok, Err, range, drop, Some, None, Vec};
760     use prelude::v1::{Path, String, Reader, Writer, Clone};
761     use prelude::v1::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath};
762     use io::fs::PathExtensions;
763     use io::timer::*;
764     use rt::running_on_valgrind;
765     use str;
766     use super::{CreatePipe};
767     use super::{InheritFd, Process, PleaseExitSignal, Command, ProcessOutput};
768     use sync::mpsc::channel;
769     use thread::Thread;
770     use time::Duration;
771
772     // FIXME(#10380) these tests should not all be ignored on android.
773
774     #[cfg(not(target_os="android"))]
775     #[test]
776     fn smoke() {
777         let p = Command::new("true").spawn();
778         assert!(p.is_ok());
779         let mut p = p.unwrap();
780         assert!(p.wait().unwrap().success());
781     }
782
783     #[cfg(not(target_os="android"))]
784     #[test]
785     fn smoke_failure() {
786         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
787             Ok(..) => panic!(),
788             Err(..) => {}
789         }
790     }
791
792     #[cfg(not(target_os="android"))]
793     #[test]
794     fn exit_reported_right() {
795         let p = Command::new("false").spawn();
796         assert!(p.is_ok());
797         let mut p = p.unwrap();
798         assert!(p.wait().unwrap().matches_exit_status(1));
799         drop(p.wait().clone());
800     }
801
802     #[cfg(all(unix, not(target_os="android")))]
803     #[test]
804     fn signal_reported_right() {
805         let p = Command::new("/bin/sh").arg("-c").arg("kill -1 $$").spawn();
806         assert!(p.is_ok());
807         let mut p = p.unwrap();
808         match p.wait().unwrap() {
809             process::ExitSignal(1) => {},
810             result => panic!("not terminated by signal 1 (instead, {})", result),
811         }
812     }
813
814     pub fn read_all(input: &mut Reader) -> String {
815         input.read_to_string().unwrap()
816     }
817
818     pub fn run_output(cmd: Command) -> String {
819         let p = cmd.spawn();
820         assert!(p.is_ok());
821         let mut p = p.unwrap();
822         assert!(p.stdout.is_some());
823         let ret = read_all(p.stdout.as_mut().unwrap() as &mut Reader);
824         assert!(p.wait().unwrap().success());
825         return ret;
826     }
827
828     #[cfg(not(target_os="android"))]
829     #[test]
830     fn stdout_works() {
831         let mut cmd = Command::new("echo");
832         cmd.arg("foobar").stdout(CreatePipe(false, true));
833         assert_eq!(run_output(cmd), "foobar\n");
834     }
835
836     #[cfg(all(unix, not(target_os="android")))]
837     #[test]
838     fn set_cwd_works() {
839         let mut cmd = Command::new("/bin/sh");
840         cmd.arg("-c").arg("pwd")
841            .cwd(&Path::new("/"))
842            .stdout(CreatePipe(false, true));
843         assert_eq!(run_output(cmd), "/\n");
844     }
845
846     #[cfg(all(unix, not(target_os="android")))]
847     #[test]
848     fn stdin_works() {
849         let mut p = Command::new("/bin/sh")
850                             .arg("-c").arg("read line; echo $line")
851                             .stdin(CreatePipe(true, false))
852                             .stdout(CreatePipe(false, true))
853                             .spawn().unwrap();
854         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
855         drop(p.stdin.take());
856         let out = read_all(p.stdout.as_mut().unwrap() as &mut Reader);
857         assert!(p.wait().unwrap().success());
858         assert_eq!(out, "foobar\n");
859     }
860
861     #[cfg(not(target_os="android"))]
862     #[test]
863     fn detach_works() {
864         let mut p = Command::new("true").detached().spawn().unwrap();
865         assert!(p.wait().unwrap().success());
866     }
867
868     #[cfg(windows)]
869     #[test]
870     fn uid_fails_on_windows() {
871         assert!(Command::new("test").uid(10).spawn().is_err());
872     }
873
874     #[cfg(all(unix, not(target_os="android")))]
875     #[test]
876     fn uid_works() {
877         use libc;
878         let mut p = Command::new("/bin/sh")
879                             .arg("-c").arg("true")
880                             .uid(unsafe { libc::getuid() as uint })
881                             .gid(unsafe { libc::getgid() as uint })
882                             .spawn().unwrap();
883         assert!(p.wait().unwrap().success());
884     }
885
886     #[cfg(all(unix, not(target_os="android")))]
887     #[test]
888     fn uid_to_root_fails() {
889         use libc;
890
891         // if we're already root, this isn't a valid test. Most of the bots run
892         // as non-root though (android is an exception).
893         if unsafe { libc::getuid() == 0 } { return }
894         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
895     }
896
897     #[cfg(not(target_os="android"))]
898     #[test]
899     fn test_process_status() {
900         let mut status = Command::new("false").status().unwrap();
901         assert!(status.matches_exit_status(1));
902
903         status = Command::new("true").status().unwrap();
904         assert!(status.success());
905     }
906
907     #[test]
908     fn test_process_output_fail_to_start() {
909         match Command::new("/no-binary-by-this-name-should-exist").output() {
910             Err(e) => assert_eq!(e.kind, FileNotFound),
911             Ok(..) => panic!()
912         }
913     }
914
915     #[cfg(not(target_os="android"))]
916     #[test]
917     fn test_process_output_output() {
918         let ProcessOutput {status, output, error}
919              = Command::new("echo").arg("hello").output().unwrap();
920         let output_str = str::from_utf8(output.as_slice()).unwrap();
921
922         assert!(status.success());
923         assert_eq!(output_str.trim().to_string(), "hello");
924         // FIXME #7224
925         if !running_on_valgrind() {
926             assert_eq!(error, Vec::new());
927         }
928     }
929
930     #[cfg(not(target_os="android"))]
931     #[test]
932     fn test_process_output_error() {
933         let ProcessOutput {status, output, error}
934              = Command::new("mkdir").arg(".").output().unwrap();
935
936         assert!(status.matches_exit_status(1));
937         assert_eq!(output, Vec::new());
938         assert!(!error.is_empty());
939     }
940
941     #[cfg(not(target_os="android"))]
942     #[test]
943     fn test_finish_once() {
944         let mut prog = Command::new("false").spawn().unwrap();
945         assert!(prog.wait().unwrap().matches_exit_status(1));
946     }
947
948     #[cfg(not(target_os="android"))]
949     #[test]
950     fn test_finish_twice() {
951         let mut prog = Command::new("false").spawn().unwrap();
952         assert!(prog.wait().unwrap().matches_exit_status(1));
953         assert!(prog.wait().unwrap().matches_exit_status(1));
954     }
955
956     #[cfg(not(target_os="android"))]
957     #[test]
958     fn test_wait_with_output_once() {
959         let prog = Command::new("echo").arg("hello").spawn().unwrap();
960         let ProcessOutput {status, output, error} = prog.wait_with_output().unwrap();
961         let output_str = str::from_utf8(output.as_slice()).unwrap();
962
963         assert!(status.success());
964         assert_eq!(output_str.trim().to_string(), "hello");
965         // FIXME #7224
966         if !running_on_valgrind() {
967             assert_eq!(error, Vec::new());
968         }
969     }
970
971     #[cfg(all(unix, not(target_os="android")))]
972     pub fn pwd_cmd() -> Command {
973         Command::new("pwd")
974     }
975     #[cfg(target_os="android")]
976     pub fn pwd_cmd() -> Command {
977         let mut cmd = Command::new("/system/bin/sh");
978         cmd.arg("-c").arg("pwd");
979         cmd
980     }
981
982     #[cfg(windows)]
983     pub fn pwd_cmd() -> Command {
984         let mut cmd = Command::new("cmd");
985         cmd.arg("/c").arg("cd");
986         cmd
987     }
988
989     #[test]
990     fn test_keep_current_working_dir() {
991         use os;
992         let prog = pwd_cmd().spawn().unwrap();
993
994         let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
995         let parent_dir = os::getcwd().unwrap();
996         let child_dir = Path::new(output.trim());
997
998         let parent_stat = parent_dir.stat().unwrap();
999         let child_stat = child_dir.stat().unwrap();
1000
1001         assert_eq!(parent_stat.unstable.device, child_stat.unstable.device);
1002         assert_eq!(parent_stat.unstable.inode, child_stat.unstable.inode);
1003     }
1004
1005     #[test]
1006     fn test_change_working_directory() {
1007         use os;
1008         // test changing to the parent of os::getcwd() because we know
1009         // the path exists (and os::getcwd() is not expected to be root)
1010         let parent_dir = os::getcwd().unwrap().dir_path();
1011         let prog = pwd_cmd().cwd(&parent_dir).spawn().unwrap();
1012
1013         let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
1014         let child_dir = Path::new(output.trim());
1015
1016         let parent_stat = parent_dir.stat().unwrap();
1017         let child_stat = child_dir.stat().unwrap();
1018
1019         assert_eq!(parent_stat.unstable.device, child_stat.unstable.device);
1020         assert_eq!(parent_stat.unstable.inode, child_stat.unstable.inode);
1021     }
1022
1023     #[cfg(all(unix, not(target_os="android")))]
1024     pub fn env_cmd() -> Command {
1025         Command::new("env")
1026     }
1027     #[cfg(target_os="android")]
1028     pub fn env_cmd() -> Command {
1029         let mut cmd = Command::new("/system/bin/sh");
1030         cmd.arg("-c").arg("set");
1031         cmd
1032     }
1033
1034     #[cfg(windows)]
1035     pub fn env_cmd() -> Command {
1036         let mut cmd = Command::new("cmd");
1037         cmd.arg("/c").arg("set");
1038         cmd
1039     }
1040
1041     #[cfg(not(target_os="android"))]
1042     #[test]
1043     fn test_inherit_env() {
1044         use os;
1045         if running_on_valgrind() { return; }
1046
1047         let prog = env_cmd().spawn().unwrap();
1048         let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
1049
1050         let r = os::env();
1051         for &(ref k, ref v) in r.iter() {
1052             // don't check windows magical empty-named variables
1053             assert!(k.is_empty() ||
1054                     output.contains(format!("{}={}", *k, *v).as_slice()),
1055                     "output doesn't contain `{}={}`\n{}",
1056                     k, v, output);
1057         }
1058     }
1059     #[cfg(target_os="android")]
1060     #[test]
1061     fn test_inherit_env() {
1062         use os;
1063         if running_on_valgrind() { return; }
1064
1065         let mut prog = env_cmd().spawn().unwrap();
1066         let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
1067
1068         let r = os::env();
1069         for &(ref k, ref v) in r.iter() {
1070             // don't check android RANDOM variables
1071             if *k != "RANDOM".to_string() {
1072                 assert!(output.contains(format!("{}={}",
1073                                                 *k,
1074                                                 *v).as_slice()) ||
1075                         output.contains(format!("{}=\'{}\'",
1076                                                 *k,
1077                                                 *v).as_slice()));
1078             }
1079         }
1080     }
1081
1082     #[test]
1083     fn test_override_env() {
1084         use os;
1085         let mut new_env = vec![("RUN_TEST_NEW_ENV", "123")];
1086
1087         // In some build environments (such as chrooted Nix builds), `env` can
1088         // only be found in the explicitly-provided PATH env variable, not in
1089         // default places such as /bin or /usr/bin. So we need to pass through
1090         // PATH to our sub-process.
1091         let path_val: String;
1092         match os::getenv("PATH") {
1093             None => {}
1094             Some(val) => {
1095                 path_val = val;
1096                 new_env.push(("PATH", path_val.as_slice()))
1097             }
1098         }
1099
1100         let prog = env_cmd().env_set_all(new_env.as_slice()).spawn().unwrap();
1101         let result = prog.wait_with_output().unwrap();
1102         let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
1103
1104         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1105                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1106     }
1107
1108     #[test]
1109     fn test_add_to_env() {
1110         let prog = env_cmd().env("RUN_TEST_NEW_ENV", "123").spawn().unwrap();
1111         let result = prog.wait_with_output().unwrap();
1112         let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
1113
1114         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1115                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1116     }
1117
1118     #[cfg(unix)]
1119     pub fn sleeper() -> Process {
1120         Command::new("sleep").arg("1000").spawn().unwrap()
1121     }
1122     #[cfg(windows)]
1123     pub fn sleeper() -> Process {
1124         // There's a `timeout` command on windows, but it doesn't like having
1125         // its output piped, so instead just ping ourselves a few times with
1126         // gaps in between so we're sure this process is alive for awhile
1127         Command::new("ping").arg("127.0.0.1").arg("-n").arg("1000").spawn().unwrap()
1128     }
1129
1130     #[test]
1131     fn test_kill() {
1132         let mut p = sleeper();
1133         Process::kill(p.id(), PleaseExitSignal).unwrap();
1134         assert!(!p.wait().unwrap().success());
1135     }
1136
1137     #[test]
1138     fn test_exists() {
1139         let mut p = sleeper();
1140         assert!(Process::kill(p.id(), 0).is_ok());
1141         p.signal_kill().unwrap();
1142         assert!(!p.wait().unwrap().success());
1143     }
1144
1145     #[test]
1146     fn test_zero() {
1147         let mut p = sleeper();
1148         p.signal_kill().unwrap();
1149         for _ in range(0i, 20) {
1150             if p.signal(0).is_err() {
1151                 assert!(!p.wait().unwrap().success());
1152                 return
1153             }
1154             timer::sleep(Duration::milliseconds(100));
1155         }
1156         panic!("never saw the child go away");
1157     }
1158
1159     #[test]
1160     fn wait_timeout() {
1161         let mut p = sleeper();
1162         p.set_timeout(Some(10));
1163         assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1164         assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1165         p.signal_kill().unwrap();
1166         p.set_timeout(None);
1167         assert!(p.wait().is_ok());
1168     }
1169
1170     #[test]
1171     fn wait_timeout2() {
1172         let (tx, rx) = channel();
1173         let tx2 = tx.clone();
1174         let _t = Thread::spawn(move|| {
1175             let mut p = sleeper();
1176             p.set_timeout(Some(10));
1177             assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1178             p.signal_kill().unwrap();
1179             tx.send(()).unwrap();
1180         });
1181         let _t = Thread::spawn(move|| {
1182             let mut p = sleeper();
1183             p.set_timeout(Some(10));
1184             assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1185             p.signal_kill().unwrap();
1186             tx2.send(()).unwrap();
1187         });
1188         rx.recv().unwrap();
1189         rx.recv().unwrap();
1190     }
1191
1192     #[test]
1193     fn forget() {
1194         let p = sleeper();
1195         let id = p.id();
1196         p.forget();
1197         assert!(Process::kill(id, 0).is_ok());
1198         assert!(Process::kill(id, PleaseExitSignal).is_ok());
1199     }
1200
1201     #[test]
1202     fn dont_close_fd_on_command_spawn() {
1203         use sys::fs;
1204
1205         let path = if cfg!(windows) {
1206             Path::new("NUL")
1207         } else {
1208             Path::new("/dev/null")
1209         };
1210
1211         let fdes = match fs::open(&path, Truncate, Write) {
1212             Ok(f) => f,
1213             Err(_) => panic!("failed to open file descriptor"),
1214         };
1215
1216         let mut cmd = pwd_cmd();
1217         let _ = cmd.stdout(InheritFd(fdes.fd()));
1218         assert!(cmd.status().unwrap().success());
1219         assert!(fdes.write("extra write\n".as_bytes()).is_ok());
1220     }
1221
1222     #[test]
1223     #[cfg(windows)]
1224     fn env_map_keys_ci() {
1225         use ffi::CString;
1226         use super::EnvKey;
1227         let mut cmd = Command::new("");
1228         cmd.env("path", "foo");
1229         cmd.env("Path", "bar");
1230         let env = &cmd.env.unwrap();
1231         let val = env.get(&EnvKey(CString::from_slice(b"PATH")));
1232         assert!(val.unwrap() == &CString::from_slice(b"bar"));
1233     }
1234 }