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.
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.
11 //! Bindings for executing child processes
14 #![allow(non_upper_case_globals)]
16 pub use self::StdioContainer::*;
17 pub use self::ProcessExit::*;
21 use collections::HashMap;
24 use io::pipe::{PipeStream, PipePair};
25 use io::{IoResult, IoError};
29 use path::BytesContainer;
30 use sync::mpsc::{channel, Receiver};
31 use sys::fs::FileDesc;
32 use sys::process::Process as ProcessImp;
36 #[cfg(windows)] use hash;
37 #[cfg(windows)] use str;
39 /// Signal a process to exit, without forcibly killing it. Corresponds to
40 /// SIGTERM on unix platforms.
41 #[cfg(windows)] pub const PleaseExitSignal: int = 15;
42 /// Signal a process to exit immediately, forcibly killing it. Corresponds to
43 /// SIGKILL on unix platforms.
44 #[cfg(windows)] pub const MustDieSignal: int = 9;
45 /// Signal a process to exit, without forcibly killing it. Corresponds to
46 /// SIGTERM on unix platforms.
47 #[cfg(not(windows))] pub const PleaseExitSignal: int = libc::SIGTERM as int;
48 /// Signal a process to exit immediately, forcibly killing it. Corresponds to
49 /// SIGKILL on unix platforms.
50 #[cfg(not(windows))] pub const MustDieSignal: int = libc::SIGKILL as int;
52 /// Representation of a running or exited child process.
54 /// This structure is used to represent and manage child processes. A child
55 /// process is created via the `Command` struct, which configures the spawning
56 /// process and can itself be constructed using a builder-style interface.
61 /// use std::io::Command;
63 /// let mut child = match Command::new("/bin/cat").arg("file.txt").spawn() {
64 /// Ok(child) => child,
65 /// Err(e) => panic!("failed to execute child: {}", e),
68 /// let contents = child.stdout.as_mut().unwrap().read_to_end();
69 /// assert!(child.wait().unwrap().success());
75 /// None until wait() is called.
76 exit_code: Option<ProcessExit>,
78 /// Manually delivered signal
79 exit_signal: Option<int>,
81 /// Deadline after which wait() will return
84 /// Handle to the child's stdin, if the `stdin` field of this process's
85 /// `ProcessConfig` was `CreatePipe`. By default, this handle is `Some`.
86 pub stdin: Option<PipeStream>,
88 /// Handle to the child's stdout, if the `stdout` field of this process's
89 /// `ProcessConfig` was `CreatePipe`. By default, this handle is `Some`.
90 pub stdout: Option<PipeStream>,
92 /// Handle to the child's stderr, if the `stderr` field of this process's
93 /// `ProcessConfig` was `CreatePipe`. By default, this handle is `Some`.
94 pub stderr: Option<PipeStream>,
97 /// A representation of environment variable name
98 /// It compares case-insensitive on Windows and case-sensitive everywhere else.
100 #[derive(Hash, PartialEq, Eq, Clone, Show)]
101 struct EnvKey(CString);
105 #[derive(Eq, Clone, Show)]
106 struct EnvKey(CString);
109 impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for EnvKey {
110 fn hash(&self, state: &mut H) {
111 let &EnvKey(ref x) = self;
112 match str::from_utf8(x.as_bytes()) {
113 Ok(s) => for ch in s.chars() {
114 (ch as u8 as char).to_lowercase().hash(state);
116 Err(..) => x.hash(state)
122 impl PartialEq for EnvKey {
123 fn eq(&self, other: &EnvKey) -> bool {
124 let &EnvKey(ref x) = self;
125 let &EnvKey(ref y) = other;
126 match (str::from_utf8(x.as_bytes()), str::from_utf8(y.as_bytes())) {
127 (Ok(xs), Ok(ys)) => {
128 if xs.len() != ys.len() {
131 for (xch, ych) in xs.chars().zip(ys.chars()) {
132 if xch.to_lowercase() != ych.to_lowercase() {
139 // If either is not a valid utf8 string, just compare them byte-wise
145 impl BytesContainer for EnvKey {
146 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
147 let &EnvKey(ref k) = self;
148 k.container_as_bytes()
152 /// A HashMap representation of environment variables.
153 pub type EnvMap = HashMap<EnvKey, CString>;
155 /// The `Command` type acts as a process builder, providing fine-grained control
156 /// over how a new process should be spawned. A default configuration can be
157 /// generated using `Command::new(program)`, where `program` gives a path to the
158 /// program to be executed. Additional builder methods allow the configuration
159 /// to be changed (for example, by adding arguments) prior to spawning:
162 /// use std::io::Command;
164 /// let mut process = match Command::new("sh").arg("-c").arg("echo hello").spawn() {
166 /// Err(e) => panic!("failed to execute process: {}", e),
169 /// let output = process.stdout.as_mut().unwrap().read_to_end();
173 // The internal data for the builder. Documented by the builder
174 // methods below, and serialized into rt::rtio::ProcessConfig.
178 cwd: Option<CString>,
179 stdin: StdioContainer,
180 stdout: StdioContainer,
181 stderr: StdioContainer,
187 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
188 // we cannot usefully take BytesContainer arguments by reference (without forcing an
189 // additional & around &str). So we are instead temporarily adding an instance
190 // for &Path, so that we can take BytesContainer as owned. When DST lands, the &Path
191 // instance should be removed, and arguments bound by BytesContainer should be passed by
192 // reference. (Here: {new, arg, args, env}.)
195 /// Constructs a new `Command` for launching the program at
196 /// path `program`, with the following default configuration:
198 /// * No arguments to the program
199 /// * Inherit the current process's environment
200 /// * Inherit the current process's working directory
201 /// * A readable pipe for stdin (file descriptor 0)
202 /// * A writeable pipe for stdout and stderr (file descriptors 1 and 2)
204 /// Builder methods are provided to change these defaults and
205 /// otherwise configure the process.
206 pub fn new<T: BytesContainer>(program: T) -> Command {
208 program: CString::from_slice(program.container_as_bytes()),
212 stdin: CreatePipe(true, false),
213 stdout: CreatePipe(false, true),
214 stderr: CreatePipe(false, true),
221 /// Add an argument to pass to the program.
222 pub fn arg<'a, T: BytesContainer>(&'a mut self, arg: T) -> &'a mut Command {
223 self.args.push(CString::from_slice(arg.container_as_bytes()));
227 /// Add multiple arguments to pass to the program.
228 pub fn args<'a, T: BytesContainer>(&'a mut self, args: &[T]) -> &'a mut Command {
229 self.args.extend(args.iter().map(|arg| {
230 CString::from_slice(arg.container_as_bytes())
234 // Get a mutable borrow of the environment variable map for this `Command`.
235 fn get_env_map<'a>(&'a mut self) -> &'a mut EnvMap {
237 Some(ref mut map) => map,
239 // if the env is currently just inheriting from the parent's,
240 // materialize the parent's env into a hashtable.
241 self.env = Some(os::env_as_bytes().into_iter().map(|(k, v)| {
242 (EnvKey(CString::from_slice(k.as_slice())),
243 CString::from_slice(v.as_slice()))
245 self.env.as_mut().unwrap()
250 /// Inserts or updates an environment variable mapping.
252 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
253 /// and case-sensitive on all other platforms.
254 pub fn env<'a, T, U>(&'a mut self, key: T, val: U)
256 where T: BytesContainer, U: BytesContainer {
257 let key = EnvKey(CString::from_slice(key.container_as_bytes()));
258 let val = CString::from_slice(val.container_as_bytes());
259 self.get_env_map().insert(key, val);
263 /// Removes an environment variable mapping.
264 pub fn env_remove<'a, T>(&'a mut self, key: T) -> &'a mut Command
265 where T: BytesContainer {
266 let key = EnvKey(CString::from_slice(key.container_as_bytes()));
267 self.get_env_map().remove(&key);
271 /// Sets the entire environment map for the child process.
273 /// If the given slice contains multiple instances of an environment
274 /// variable, the *rightmost* instance will determine the value.
275 pub fn env_set_all<'a, T, U>(&'a mut self, env: &[(T,U)])
277 where T: BytesContainer, U: BytesContainer {
278 self.env = Some(env.iter().map(|&(ref k, ref v)| {
279 (EnvKey(CString::from_slice(k.container_as_bytes())),
280 CString::from_slice(v.container_as_bytes()))
285 /// Set the working directory for the child process.
286 pub fn cwd<'a>(&'a mut self, dir: &Path) -> &'a mut Command {
287 self.cwd = Some(CString::from_slice(dir.as_vec()));
291 /// Configuration for the child process's stdin handle (file descriptor 0).
292 /// Defaults to `CreatePipe(true, false)` so the input can be written to.
293 pub fn stdin<'a>(&'a mut self, cfg: StdioContainer) -> &'a mut Command {
298 /// Configuration for the child process's stdout handle (file descriptor 1).
299 /// Defaults to `CreatePipe(false, true)` so the output can be collected.
300 pub fn stdout<'a>(&'a mut self, cfg: StdioContainer) -> &'a mut Command {
305 /// Configuration for the child process's stderr handle (file descriptor 2).
306 /// Defaults to `CreatePipe(false, true)` so the output can be collected.
307 pub fn stderr<'a>(&'a mut self, cfg: StdioContainer) -> &'a mut Command {
312 /// Sets the child process's user id. This translates to a `setuid` call in
313 /// the child process. Setting this value on windows will cause the spawn to
314 /// fail. Failure in the `setuid` call on unix will also cause the spawn to
316 pub fn uid<'a>(&'a mut self, id: uint) -> &'a mut Command {
321 /// Similar to `uid`, but sets the group id of the child process. This has
322 /// the same semantics as the `uid` field.
323 pub fn gid<'a>(&'a mut self, id: uint) -> &'a mut Command {
328 /// Sets the child process to be spawned in a detached state. On unix, this
329 /// means that the child is the leader of a new process group.
330 pub fn detached<'a>(&'a mut self) -> &'a mut Command {
335 /// Executes the command as a child process, which is returned.
336 pub fn spawn(&self) -> IoResult<Process> {
337 let (their_stdin, our_stdin) = try!(setup_io(self.stdin));
338 let (their_stdout, our_stdout) = try!(setup_io(self.stdout));
339 let (their_stderr, our_stderr) = try!(setup_io(self.stderr));
341 match ProcessImp::spawn(self, their_stdin, their_stdout, their_stderr) {
343 Ok(handle) => Ok(Process {
356 /// Executes the command as a child process, waiting for it to finish and
357 /// collecting all of its output.
362 /// use std::io::Command;
364 /// let output = match Command::new("cat").arg("foot.txt").output() {
365 /// Ok(output) => output,
366 /// Err(e) => panic!("failed to execute process: {}", e),
369 /// println!("status: {}", output.status);
370 /// println!("stdout: {}", String::from_utf8_lossy(output.output.as_slice()));
371 /// println!("stderr: {}", String::from_utf8_lossy(output.error.as_slice()));
373 pub fn output(&self) -> IoResult<ProcessOutput> {
374 self.spawn().and_then(|p| p.wait_with_output())
377 /// Executes a command as a child process, waiting for it to finish and
378 /// collecting its exit status.
383 /// use std::io::Command;
385 /// let status = match Command::new("ls").status() {
386 /// Ok(status) => status,
387 /// Err(e) => panic!("failed to execute process: {}", e),
390 /// println!("process exited with: {}", status);
392 pub fn status(&self) -> IoResult<ProcessExit> {
393 self.spawn().and_then(|mut p| p.wait())
397 impl fmt::String for Command {
398 /// Format the program and arguments of a Command for display. Any
399 /// non-utf8 data is lossily converted using the utf8 replacement
401 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
402 try!(write!(f, "{}", String::from_utf8_lossy(self.program.as_bytes())));
403 for arg in self.args.iter() {
404 try!(write!(f, " '{}'", String::from_utf8_lossy(arg.as_bytes())));
410 fn setup_io(io: StdioContainer) -> IoResult<(Option<PipeStream>, Option<PipeStream>)> {
419 theirs = Some(PipeStream::from_filedesc(FileDesc::new(fd, false)));
422 CreatePipe(readable, _writable) => {
423 let PipePair { reader, writer } = try!(PipeStream::pair());
425 theirs = Some(reader);
428 theirs = Some(writer);
436 // Allow the sys module to get access to the Command state
437 impl sys::process::ProcessConfig<EnvKey, CString> for Command {
438 fn program(&self) -> &CString {
441 fn args(&self) -> &[CString] {
444 fn env(&self) -> Option<&EnvMap> {
447 fn cwd(&self) -> Option<&CString> {
450 fn uid(&self) -> Option<uint> {
453 fn gid(&self) -> Option<uint> {
456 fn detach(&self) -> bool {
462 /// The output of a finished process.
463 #[derive(PartialEq, Eq, Clone)]
464 pub struct ProcessOutput {
465 /// The status (exit code) of the process.
466 pub status: ProcessExit,
467 /// The data that the process wrote to stdout.
469 /// The data that the process wrote to stderr.
473 /// Describes what to do with a standard io stream for a child process.
474 #[derive(Clone, Copy)]
475 pub enum StdioContainer {
476 /// This stream will be ignored. This is the equivalent of attaching the
477 /// stream to `/dev/null`
480 /// The specified file descriptor is inherited for the stream which it is
481 /// specified for. Ownership of the file descriptor is *not* taken, so the
482 /// caller must clean it up.
483 InheritFd(libc::c_int),
485 /// Creates a pipe for the specified file descriptor which will be created
486 /// when the process is spawned.
488 /// The first boolean argument is whether the pipe is readable, and the
489 /// second is whether it is writable. These properties are from the view of
490 /// the *child* process, not the parent process.
491 CreatePipe(bool /* readable */, bool /* writable */),
494 /// Describes the result of a process after it has terminated.
495 /// Note that Windows have no signals, so the result is usually ExitStatus.
496 #[derive(PartialEq, Eq, Clone, Copy)]
497 pub enum ProcessExit {
498 /// Normal termination with an exit status.
501 /// Termination by signal, with the signal number.
505 impl fmt::Show for ProcessExit {
506 /// Format a ProcessExit enum, to nicely present the information.
507 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
508 fmt::String::fmt(self, f)
513 impl fmt::String for ProcessExit {
514 /// Format a ProcessExit enum, to nicely present the information.
515 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
517 ExitStatus(code) => write!(f, "exit code: {}", code),
518 ExitSignal(code) => write!(f, "signal: {}", code),
524 /// Was termination successful? Signal termination not considered a success,
525 /// and success is defined as a zero exit status.
526 pub fn success(&self) -> bool {
527 return self.matches_exit_status(0);
530 /// Checks whether this ProcessExit matches the given exit status.
531 /// Termination by signal will never match an exit code.
532 pub fn matches_exit_status(&self, wanted: int) -> bool {
533 *self == ExitStatus(wanted)
538 /// Sends `signal` to another process in the system identified by `id`.
540 /// Note that windows doesn't quite have the same model as unix, so some
541 /// unix signals are mapped to windows signals. Notably, unix termination
542 /// signals (SIGTERM/SIGKILL/SIGINT) are translated to `TerminateProcess`.
544 /// Additionally, a signal number of 0 can check for existence of the target
545 /// process. Note, though, that on some platforms signals will continue to
546 /// be successfully delivered if the child has exited, but not yet been
548 pub fn kill(id: libc::pid_t, signal: int) -> IoResult<()> {
549 unsafe { ProcessImp::killpid(id, signal) }
552 /// Returns the process id of this child process
553 pub fn id(&self) -> libc::pid_t { self.handle.id() }
555 /// Sends the specified signal to the child process, returning whether the
556 /// signal could be delivered or not.
558 /// Note that signal 0 is interpreted as a poll to check whether the child
559 /// process is still alive or not. If an error is returned, then the child
560 /// process has exited.
562 /// On some unix platforms signals will continue to be received after a
563 /// child has exited but not yet been reaped. In order to report the status
564 /// of signal delivery correctly, unix implementations may invoke
565 /// `waitpid()` with `WNOHANG` in order to reap the child as necessary.
569 /// If the signal delivery fails, the corresponding error is returned.
570 pub fn signal(&mut self, signal: int) -> IoResult<()> {
571 #[cfg(unix)] fn collect_status(p: &mut Process) {
572 // On Linux (and possibly other unices), a process that has exited will
573 // continue to accept signals because it is "defunct". The delivery of
574 // signals will only fail once the child has been reaped. For this
575 // reason, if the process hasn't exited yet, then we attempt to collect
576 // their status with WNOHANG.
577 if p.exit_code.is_none() {
578 match p.handle.try_wait() {
579 Some(code) => { p.exit_code = Some(code); }
584 #[cfg(windows)] fn collect_status(_p: &mut Process) {}
586 collect_status(self);
588 // if the process has finished, and therefore had waitpid called,
589 // and we kill it, then on unix we might ending up killing a
590 // newer process that happens to have the same (re-used) id
591 if self.exit_code.is_some() {
593 kind: io::InvalidInput,
594 desc: "invalid argument: can't kill an exited process",
599 // A successfully delivered signal that isn't 0 (just a poll for being
600 // alive) is recorded for windows (see wait())
601 match unsafe { self.handle.kill(signal) } {
602 Ok(()) if signal == 0 => Ok(()),
603 Ok(()) => { self.exit_signal = Some(signal); Ok(()) }
609 /// Sends a signal to this child requesting that it exits. This is
610 /// equivalent to sending a SIGTERM on unix platforms.
611 pub fn signal_exit(&mut self) -> IoResult<()> {
612 self.signal(PleaseExitSignal)
615 /// Sends a signal to this child forcing it to exit. This is equivalent to
616 /// sending a SIGKILL on unix platforms.
617 pub fn signal_kill(&mut self) -> IoResult<()> {
618 self.signal(MustDieSignal)
621 /// Wait for the child to exit completely, returning the status that it
622 /// exited with. This function will continue to have the same return value
623 /// after it has been called at least once.
625 /// The stdin handle to the child process will be closed before waiting.
629 /// This function can fail if a timeout was previously specified via
630 /// `set_timeout` and the timeout expires before the child exits.
631 pub fn wait(&mut self) -> IoResult<ProcessExit> {
632 drop(self.stdin.take());
633 match self.exit_code {
634 Some(code) => Ok(code),
636 let code = try!(self.handle.wait(self.deadline));
637 // On windows, waitpid will never return a signal. If a signal
638 // was successfully delivered to the process, however, we can
639 // consider it as having died via a signal.
640 let code = match self.exit_signal {
642 Some(signal) if cfg!(windows) => ExitSignal(signal),
645 self.exit_code = Some(code);
651 /// Sets a timeout, in milliseconds, for future calls to wait().
653 /// The argument specified is a relative distance into the future, in
654 /// milliseconds, after which any call to wait() will return immediately
655 /// with a timeout error, and all future calls to wait() will not block.
657 /// A value of `None` will clear any previous timeout, and a value of `Some`
658 /// will override any previously set timeout.
663 /// # #![allow(unstable)]
664 /// use std::io::{Command, IoResult};
665 /// use std::io::process::ProcessExit;
667 /// fn run_gracefully(prog: &str) -> IoResult<ProcessExit> {
668 /// let mut p = try!(Command::new("long-running-process").spawn());
670 /// // give the process 10 seconds to finish completely
671 /// p.set_timeout(Some(10_000));
673 /// Ok(status) => return Ok(status),
677 /// // Attempt to exit gracefully, but don't wait for it too long
678 /// try!(p.signal_exit());
679 /// p.set_timeout(Some(1_000));
681 /// Ok(status) => return Ok(status),
685 /// // Well, we did our best, forcefully kill the process
686 /// try!(p.signal_kill());
687 /// p.set_timeout(None);
691 #[unstable = "the type of the timeout is likely to change"]
692 pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
693 self.deadline = timeout_ms.map(|i| i + sys::timer::now()).unwrap_or(0);
696 /// Simultaneously wait for the child to exit and collect all remaining
697 /// output on the stdout/stderr handles, returning a `ProcessOutput`
700 /// The stdin handle to the child is closed before waiting.
704 /// This function can fail for any of the same reasons that `wait()` can
706 pub fn wait_with_output(mut self) -> IoResult<ProcessOutput> {
707 drop(self.stdin.take());
708 fn read(stream: Option<io::PipeStream>) -> Receiver<IoResult<Vec<u8>>> {
709 let (tx, rx) = channel();
712 Thread::spawn(move |:| {
713 let mut stream = stream;
714 tx.send(stream.read_to_end()).unwrap();
717 None => tx.send(Ok(Vec::new())).unwrap()
721 let stdout = read(self.stdout.take());
722 let stderr = read(self.stderr.take());
724 let status = try!(self.wait());
728 output: stdout.recv().unwrap().unwrap_or(Vec::new()),
729 error: stderr.recv().unwrap().unwrap_or(Vec::new()),
733 /// Forgets this process, allowing it to outlive the parent
735 /// This function will forcefully prevent calling `wait()` on the child
736 /// process in the destructor, allowing the child to outlive the
737 /// parent. Note that this operation can easily lead to leaking the
738 /// resources of the child process, so care must be taken when
739 /// invoking this method.
740 pub fn forget(mut self) {
745 impl Drop for Process {
747 if self.forget { return }
749 // Close all I/O before exiting to ensure that the child doesn't wait
750 // forever to print some text or something similar.
751 drop(self.stdin.take());
752 drop(self.stdout.take());
753 drop(self.stderr.take());
755 self.set_timeout(None);
756 let _ = self.wait().unwrap();
762 use io::{Truncate, Write, TimedOut, timer, process, FileNotFound};
763 use prelude::v1::{Ok, Err, range, drop, Some, None, Vec};
764 use prelude::v1::{Path, String, Reader, Writer, Clone};
765 use prelude::v1::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath};
766 use io::fs::PathExtensions;
768 use rt::running_on_valgrind;
770 use super::{CreatePipe};
771 use super::{InheritFd, Process, PleaseExitSignal, Command, ProcessOutput};
772 use sync::mpsc::channel;
776 // FIXME(#10380) these tests should not all be ignored on android.
778 #[cfg(not(target_os="android"))]
781 let p = Command::new("true").spawn();
783 let mut p = p.unwrap();
784 assert!(p.wait().unwrap().success());
787 #[cfg(not(target_os="android"))]
790 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
796 #[cfg(not(target_os="android"))]
798 fn exit_reported_right() {
799 let p = Command::new("false").spawn();
801 let mut p = p.unwrap();
802 assert!(p.wait().unwrap().matches_exit_status(1));
803 drop(p.wait().clone());
806 #[cfg(all(unix, not(target_os="android")))]
808 fn signal_reported_right() {
809 let p = Command::new("/bin/sh").arg("-c").arg("kill -1 $$").spawn();
811 let mut p = p.unwrap();
812 match p.wait().unwrap() {
813 process::ExitSignal(1) => {},
814 result => panic!("not terminated by signal 1 (instead, {})", result),
818 pub fn read_all(input: &mut Reader) -> String {
819 input.read_to_string().unwrap()
822 pub fn run_output(cmd: Command) -> String {
825 let mut p = p.unwrap();
826 assert!(p.stdout.is_some());
827 let ret = read_all(p.stdout.as_mut().unwrap() as &mut Reader);
828 assert!(p.wait().unwrap().success());
832 #[cfg(not(target_os="android"))]
835 let mut cmd = Command::new("echo");
836 cmd.arg("foobar").stdout(CreatePipe(false, true));
837 assert_eq!(run_output(cmd), "foobar\n");
840 #[cfg(all(unix, not(target_os="android")))]
843 let mut cmd = Command::new("/bin/sh");
844 cmd.arg("-c").arg("pwd")
845 .cwd(&Path::new("/"))
846 .stdout(CreatePipe(false, true));
847 assert_eq!(run_output(cmd), "/\n");
850 #[cfg(all(unix, not(target_os="android")))]
853 let mut p = Command::new("/bin/sh")
854 .arg("-c").arg("read line; echo $line")
855 .stdin(CreatePipe(true, false))
856 .stdout(CreatePipe(false, true))
858 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
859 drop(p.stdin.take());
860 let out = read_all(p.stdout.as_mut().unwrap() as &mut Reader);
861 assert!(p.wait().unwrap().success());
862 assert_eq!(out, "foobar\n");
865 #[cfg(not(target_os="android"))]
868 let mut p = Command::new("true").detached().spawn().unwrap();
869 assert!(p.wait().unwrap().success());
874 fn uid_fails_on_windows() {
875 assert!(Command::new("test").uid(10).spawn().is_err());
878 #[cfg(all(unix, not(target_os="android")))]
882 let mut p = Command::new("/bin/sh")
883 .arg("-c").arg("true")
884 .uid(unsafe { libc::getuid() as uint })
885 .gid(unsafe { libc::getgid() as uint })
887 assert!(p.wait().unwrap().success());
890 #[cfg(all(unix, not(target_os="android")))]
892 fn uid_to_root_fails() {
895 // if we're already root, this isn't a valid test. Most of the bots run
896 // as non-root though (android is an exception).
897 if unsafe { libc::getuid() == 0 } { return }
898 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
901 #[cfg(not(target_os="android"))]
903 fn test_process_status() {
904 let mut status = Command::new("false").status().unwrap();
905 assert!(status.matches_exit_status(1));
907 status = Command::new("true").status().unwrap();
908 assert!(status.success());
912 fn test_process_output_fail_to_start() {
913 match Command::new("/no-binary-by-this-name-should-exist").output() {
914 Err(e) => assert_eq!(e.kind, FileNotFound),
919 #[cfg(not(target_os="android"))]
921 fn test_process_output_output() {
922 let ProcessOutput {status, output, error}
923 = Command::new("echo").arg("hello").output().unwrap();
924 let output_str = str::from_utf8(output.as_slice()).unwrap();
926 assert!(status.success());
927 assert_eq!(output_str.trim().to_string(), "hello");
929 if !running_on_valgrind() {
930 assert_eq!(error, Vec::new());
934 #[cfg(not(target_os="android"))]
936 fn test_process_output_error() {
937 let ProcessOutput {status, output, error}
938 = Command::new("mkdir").arg(".").output().unwrap();
940 assert!(status.matches_exit_status(1));
941 assert_eq!(output, Vec::new());
942 assert!(!error.is_empty());
945 #[cfg(not(target_os="android"))]
947 fn test_finish_once() {
948 let mut prog = Command::new("false").spawn().unwrap();
949 assert!(prog.wait().unwrap().matches_exit_status(1));
952 #[cfg(not(target_os="android"))]
954 fn test_finish_twice() {
955 let mut prog = Command::new("false").spawn().unwrap();
956 assert!(prog.wait().unwrap().matches_exit_status(1));
957 assert!(prog.wait().unwrap().matches_exit_status(1));
960 #[cfg(not(target_os="android"))]
962 fn test_wait_with_output_once() {
963 let prog = Command::new("echo").arg("hello").spawn().unwrap();
964 let ProcessOutput {status, output, error} = prog.wait_with_output().unwrap();
965 let output_str = str::from_utf8(output.as_slice()).unwrap();
967 assert!(status.success());
968 assert_eq!(output_str.trim().to_string(), "hello");
970 if !running_on_valgrind() {
971 assert_eq!(error, Vec::new());
975 #[cfg(all(unix, not(target_os="android")))]
976 pub fn pwd_cmd() -> Command {
979 #[cfg(target_os="android")]
980 pub fn pwd_cmd() -> Command {
981 let mut cmd = Command::new("/system/bin/sh");
982 cmd.arg("-c").arg("pwd");
987 pub fn pwd_cmd() -> Command {
988 let mut cmd = Command::new("cmd");
989 cmd.arg("/c").arg("cd");
994 fn test_keep_current_working_dir() {
996 let prog = pwd_cmd().spawn().unwrap();
998 let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
999 let parent_dir = os::getcwd().unwrap();
1000 let child_dir = Path::new(output.trim());
1002 let parent_stat = parent_dir.stat().unwrap();
1003 let child_stat = child_dir.stat().unwrap();
1005 assert_eq!(parent_stat.unstable.device, child_stat.unstable.device);
1006 assert_eq!(parent_stat.unstable.inode, child_stat.unstable.inode);
1010 fn test_change_working_directory() {
1012 // test changing to the parent of os::getcwd() because we know
1013 // the path exists (and os::getcwd() is not expected to be root)
1014 let parent_dir = os::getcwd().unwrap().dir_path();
1015 let prog = pwd_cmd().cwd(&parent_dir).spawn().unwrap();
1017 let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
1018 let child_dir = Path::new(output.trim());
1020 let parent_stat = parent_dir.stat().unwrap();
1021 let child_stat = child_dir.stat().unwrap();
1023 assert_eq!(parent_stat.unstable.device, child_stat.unstable.device);
1024 assert_eq!(parent_stat.unstable.inode, child_stat.unstable.inode);
1027 #[cfg(all(unix, not(target_os="android")))]
1028 pub fn env_cmd() -> Command {
1031 #[cfg(target_os="android")]
1032 pub fn env_cmd() -> Command {
1033 let mut cmd = Command::new("/system/bin/sh");
1034 cmd.arg("-c").arg("set");
1039 pub fn env_cmd() -> Command {
1040 let mut cmd = Command::new("cmd");
1041 cmd.arg("/c").arg("set");
1045 #[cfg(not(target_os="android"))]
1047 fn test_inherit_env() {
1049 if running_on_valgrind() { return; }
1051 let prog = env_cmd().spawn().unwrap();
1052 let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
1055 for &(ref k, ref v) in r.iter() {
1056 // don't check windows magical empty-named variables
1057 assert!(k.is_empty() ||
1058 output.contains(format!("{}={}", *k, *v).as_slice()),
1059 "output doesn't contain `{}={}`\n{}",
1063 #[cfg(target_os="android")]
1065 fn test_inherit_env() {
1067 if running_on_valgrind() { return; }
1069 let mut prog = env_cmd().spawn().unwrap();
1070 let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
1073 for &(ref k, ref v) in r.iter() {
1074 // don't check android RANDOM variables
1075 if *k != "RANDOM".to_string() {
1076 assert!(output.contains(format!("{}={}",
1079 output.contains(format!("{}=\'{}\'",
1087 fn test_override_env() {
1089 let mut new_env = vec![("RUN_TEST_NEW_ENV", "123")];
1091 // In some build environments (such as chrooted Nix builds), `env` can
1092 // only be found in the explicitly-provided PATH env variable, not in
1093 // default places such as /bin or /usr/bin. So we need to pass through
1094 // PATH to our sub-process.
1095 let path_val: String;
1096 match os::getenv("PATH") {
1100 new_env.push(("PATH", path_val.as_slice()))
1104 let prog = env_cmd().env_set_all(new_env.as_slice()).spawn().unwrap();
1105 let result = prog.wait_with_output().unwrap();
1106 let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
1108 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1109 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1113 fn test_add_to_env() {
1114 let prog = env_cmd().env("RUN_TEST_NEW_ENV", "123").spawn().unwrap();
1115 let result = prog.wait_with_output().unwrap();
1116 let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
1118 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1119 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1123 pub fn sleeper() -> Process {
1124 Command::new("sleep").arg("1000").spawn().unwrap()
1127 pub fn sleeper() -> Process {
1128 // There's a `timeout` command on windows, but it doesn't like having
1129 // its output piped, so instead just ping ourselves a few times with
1130 // gaps in between so we're sure this process is alive for awhile
1131 Command::new("ping").arg("127.0.0.1").arg("-n").arg("1000").spawn().unwrap()
1136 let mut p = sleeper();
1137 Process::kill(p.id(), PleaseExitSignal).unwrap();
1138 assert!(!p.wait().unwrap().success());
1143 let mut p = sleeper();
1144 assert!(Process::kill(p.id(), 0).is_ok());
1145 p.signal_kill().unwrap();
1146 assert!(!p.wait().unwrap().success());
1151 let mut p = sleeper();
1152 p.signal_kill().unwrap();
1153 for _ in range(0i, 20) {
1154 if p.signal(0).is_err() {
1155 assert!(!p.wait().unwrap().success());
1158 timer::sleep(Duration::milliseconds(100));
1160 panic!("never saw the child go away");
1165 let mut p = sleeper();
1166 p.set_timeout(Some(10));
1167 assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1168 assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1169 p.signal_kill().unwrap();
1170 p.set_timeout(None);
1171 assert!(p.wait().is_ok());
1175 fn wait_timeout2() {
1176 let (tx, rx) = channel();
1177 let tx2 = tx.clone();
1178 let _t = Thread::spawn(move|| {
1179 let mut p = sleeper();
1180 p.set_timeout(Some(10));
1181 assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1182 p.signal_kill().unwrap();
1183 tx.send(()).unwrap();
1185 let _t = Thread::spawn(move|| {
1186 let mut p = sleeper();
1187 p.set_timeout(Some(10));
1188 assert_eq!(p.wait().err().unwrap().kind, TimedOut);
1189 p.signal_kill().unwrap();
1190 tx2.send(()).unwrap();
1201 assert!(Process::kill(id, 0).is_ok());
1202 assert!(Process::kill(id, PleaseExitSignal).is_ok());
1206 fn dont_close_fd_on_command_spawn() {
1209 let path = if cfg!(windows) {
1212 Path::new("/dev/null")
1215 let fdes = match fs::open(&path, Truncate, Write) {
1217 Err(_) => panic!("failed to open file descriptor"),
1220 let mut cmd = pwd_cmd();
1221 let _ = cmd.stdout(InheritFd(fdes.fd()));
1222 assert!(cmd.status().unwrap().success());
1223 assert!(fdes.write("extra write\n".as_bytes()).is_ok());
1228 fn env_map_keys_ci() {
1231 let mut cmd = Command::new("");
1232 cmd.env("path", "foo");
1233 cmd.env("Path", "bar");
1234 let env = &cmd.env.unwrap();
1235 let val = env.get(&EnvKey(CString::from_slice(b"PATH")));
1236 assert!(val.unwrap() == &CString::from_slice(b"bar"));