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 // NOTE(stage0) remove import after a snapshot
27 use io::pipe::{PipeStream, PipePair};
28 use io::{IoResult, IoError};
32 use path::BytesContainer;
33 use sync::mpsc::{channel, Receiver};
34 use sys::fs::FileDesc;
35 use sys::process::Process as ProcessImp;
39 #[cfg(windows)] use hash;
40 #[cfg(windows)] use str;
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;
55 /// Representation of a running or exited child process.
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.
64 /// use std::io::Command;
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),
71 /// let contents = child.stdout.as_mut().unwrap().read_to_end();
72 /// assert!(child.wait().unwrap().success());
78 /// None until wait() is called.
79 exit_code: Option<ProcessExit>,
81 /// Manually delivered signal
82 exit_signal: Option<int>,
84 /// Deadline after which wait() will return
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>,
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>,
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>,
100 /// A representation of environment variable name
101 /// It compares case-insensitive on Windows and case-sensitive everywhere else.
103 #[derive(Hash, PartialEq, Eq, Clone, Show)]
104 struct EnvKey(CString);
108 #[derive(Eq, Clone, Show)]
109 struct EnvKey(CString);
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);
119 Err(..) => x.hash(state)
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() {
134 for (xch, ych) in xs.chars().zip(ys.chars()) {
135 if xch.to_lowercase() != ych.to_lowercase() {
142 // If either is not a valid utf8 string, just compare them byte-wise
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()
155 /// A HashMap representation of environment variables.
156 pub type EnvMap = HashMap<EnvKey, CString>;
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:
165 /// use std::io::Command;
167 /// let mut process = match Command::new("sh").arg("-c").arg("echo hello").spawn() {
169 /// Err(e) => panic!("failed to execute process: {}", e),
172 /// let output = process.stdout.as_mut().unwrap().read_to_end();
176 // The internal data for the builder. Documented by the builder
177 // methods below, and serialized into rt::rtio::ProcessConfig.
181 cwd: Option<CString>,
182 stdin: StdioContainer,
183 stdout: StdioContainer,
184 stderr: StdioContainer,
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}.)
198 /// Constructs a new `Command` for launching the program at
199 /// path `program`, with the following default configuration:
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)
207 /// Builder methods are provided to change these defaults and
208 /// otherwise configure the process.
209 pub fn new<T: BytesContainer>(program: T) -> Command {
211 program: CString::from_slice(program.container_as_bytes()),
215 stdin: CreatePipe(true, false),
216 stdout: CreatePipe(false, true),
217 stderr: CreatePipe(false, true),
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()));
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())
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 {
240 Some(ref mut map) => map,
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()))
248 self.env.as_mut().unwrap()
253 /// Inserts or updates an environment variable mapping.
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)
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);
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);
274 /// Sets the entire environment map for the child process.
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)])
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()))
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()));
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 {
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 {
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 {
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
319 pub fn uid<'a>(&'a mut self, id: uint) -> &'a mut Command {
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 {
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 {
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));
344 match ProcessImp::spawn(self, their_stdin, their_stdout, their_stderr) {
346 Ok(handle) => Ok(Process {
359 /// Executes the command as a child process, waiting for it to finish and
360 /// collecting all of its output.
365 /// use std::io::Command;
367 /// let output = match Command::new("cat").arg("foot.txt").output() {
368 /// Ok(output) => output,
369 /// Err(e) => panic!("failed to execute process: {}", e),
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()));
376 pub fn output(&self) -> IoResult<ProcessOutput> {
377 self.spawn().and_then(|p| p.wait_with_output())
380 /// Executes a command as a child process, waiting for it to finish and
381 /// collecting its exit status.
386 /// use std::io::Command;
388 /// let status = match Command::new("ls").status() {
389 /// Ok(status) => status,
390 /// Err(e) => panic!("failed to execute process: {}", e),
393 /// println!("process exited with: {}", status);
395 pub fn status(&self) -> IoResult<ProcessExit> {
396 self.spawn().and_then(|mut p| p.wait())
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
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())));
413 fn setup_io(io: StdioContainer) -> IoResult<(Option<PipeStream>, Option<PipeStream>)> {
422 theirs = Some(PipeStream::from_filedesc(FileDesc::new(fd, false)));
425 CreatePipe(readable, _writable) => {
426 let PipePair { reader, writer } = try!(PipeStream::pair());
428 theirs = Some(reader);
431 theirs = Some(writer);
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 {
444 fn args(&self) -> &[CString] {
447 fn env(&self) -> Option<&EnvMap> {
450 fn cwd(&self) -> Option<&CString> {
453 fn uid(&self) -> Option<uint> {
456 fn gid(&self) -> Option<uint> {
459 fn detach(&self) -> bool {
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.
472 /// The data that the process wrote to stderr.
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`
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),
488 /// Creates a pipe for the specified file descriptor which will be created
489 /// when the process is spawned.
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 */),
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.
504 /// Termination by signal, with the signal number.
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 {
513 ExitStatus(code) => write!(f, "exit code: {}", code),
514 ExitSignal(code) => write!(f, "signal: {}", code),
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);
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)
534 /// Sends `signal` to another process in the system identified by `id`.
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`.
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
544 pub fn kill(id: libc::pid_t, signal: int) -> IoResult<()> {
545 unsafe { ProcessImp::killpid(id, signal) }
548 /// Returns the process id of this child process
549 pub fn id(&self) -> libc::pid_t { self.handle.id() }
551 /// Sends the specified signal to the child process, returning whether the
552 /// signal could be delivered or not.
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.
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.
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); }
580 #[cfg(windows)] fn collect_status(_p: &mut Process) {}
582 collect_status(self);
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() {
589 kind: io::InvalidInput,
590 desc: "invalid argument: can't kill an exited process",
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(()) }
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)
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)
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.
621 /// The stdin handle to the child process will be closed before waiting.
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),
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 {
638 Some(signal) if cfg!(windows) => ExitSignal(signal),
641 self.exit_code = Some(code);
647 /// Sets a timeout, in milliseconds, for future calls to wait().
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.
653 /// A value of `None` will clear any previous timeout, and a value of `Some`
654 /// will override any previously set timeout.
659 /// # #![allow(unstable)]
660 /// use std::io::{Command, IoResult};
661 /// use std::io::process::ProcessExit;
663 /// fn run_gracefully(prog: &str) -> IoResult<ProcessExit> {
664 /// let mut p = try!(Command::new("long-running-process").spawn());
666 /// // give the process 10 seconds to finish completely
667 /// p.set_timeout(Some(10_000));
669 /// Ok(status) => return Ok(status),
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));
677 /// Ok(status) => return Ok(status),
681 /// // Well, we did our best, forcefully kill the process
682 /// try!(p.signal_kill());
683 /// p.set_timeout(None);
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);
692 /// Simultaneously wait for the child to exit and collect all remaining
693 /// output on the stdout/stderr handles, returning a `ProcessOutput`
696 /// The stdin handle to the child is closed before waiting.
700 /// This function can fail for any of the same reasons that `wait()` can
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();
708 Thread::spawn(move |:| {
709 let mut stream = stream;
710 tx.send(stream.read_to_end()).unwrap();
713 None => tx.send(Ok(Vec::new())).unwrap()
717 let stdout = read(self.stdout.take());
718 let stderr = read(self.stderr.take());
720 let status = try!(self.wait());
724 output: stdout.recv().unwrap().unwrap_or(Vec::new()),
725 error: stderr.recv().unwrap().unwrap_or(Vec::new()),
729 /// Forgets this process, allowing it to outlive the parent
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) {
741 impl Drop for Process {
743 if self.forget { return }
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());
751 self.set_timeout(None);
752 let _ = self.wait().unwrap();
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;
764 use rt::running_on_valgrind;
766 use super::{CreatePipe};
767 use super::{InheritFd, Process, PleaseExitSignal, Command, ProcessOutput};
768 use sync::mpsc::channel;
772 // FIXME(#10380) these tests should not all be ignored on android.
774 #[cfg(not(target_os="android"))]
777 let p = Command::new("true").spawn();
779 let mut p = p.unwrap();
780 assert!(p.wait().unwrap().success());
783 #[cfg(not(target_os="android"))]
786 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
792 #[cfg(not(target_os="android"))]
794 fn exit_reported_right() {
795 let p = Command::new("false").spawn();
797 let mut p = p.unwrap();
798 assert!(p.wait().unwrap().matches_exit_status(1));
799 drop(p.wait().clone());
802 #[cfg(all(unix, not(target_os="android")))]
804 fn signal_reported_right() {
805 let p = Command::new("/bin/sh").arg("-c").arg("kill -1 $$").spawn();
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),
814 pub fn read_all(input: &mut Reader) -> String {
815 input.read_to_string().unwrap()
818 pub fn run_output(cmd: Command) -> String {
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());
828 #[cfg(not(target_os="android"))]
831 let mut cmd = Command::new("echo");
832 cmd.arg("foobar").stdout(CreatePipe(false, true));
833 assert_eq!(run_output(cmd), "foobar\n");
836 #[cfg(all(unix, not(target_os="android")))]
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");
846 #[cfg(all(unix, not(target_os="android")))]
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))
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");
861 #[cfg(not(target_os="android"))]
864 let mut p = Command::new("true").detached().spawn().unwrap();
865 assert!(p.wait().unwrap().success());
870 fn uid_fails_on_windows() {
871 assert!(Command::new("test").uid(10).spawn().is_err());
874 #[cfg(all(unix, not(target_os="android")))]
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 })
883 assert!(p.wait().unwrap().success());
886 #[cfg(all(unix, not(target_os="android")))]
888 fn uid_to_root_fails() {
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());
897 #[cfg(not(target_os="android"))]
899 fn test_process_status() {
900 let mut status = Command::new("false").status().unwrap();
901 assert!(status.matches_exit_status(1));
903 status = Command::new("true").status().unwrap();
904 assert!(status.success());
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),
915 #[cfg(not(target_os="android"))]
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();
922 assert!(status.success());
923 assert_eq!(output_str.trim().to_string(), "hello");
925 if !running_on_valgrind() {
926 assert_eq!(error, Vec::new());
930 #[cfg(not(target_os="android"))]
932 fn test_process_output_error() {
933 let ProcessOutput {status, output, error}
934 = Command::new("mkdir").arg(".").output().unwrap();
936 assert!(status.matches_exit_status(1));
937 assert_eq!(output, Vec::new());
938 assert!(!error.is_empty());
941 #[cfg(not(target_os="android"))]
943 fn test_finish_once() {
944 let mut prog = Command::new("false").spawn().unwrap();
945 assert!(prog.wait().unwrap().matches_exit_status(1));
948 #[cfg(not(target_os="android"))]
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));
956 #[cfg(not(target_os="android"))]
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();
963 assert!(status.success());
964 assert_eq!(output_str.trim().to_string(), "hello");
966 if !running_on_valgrind() {
967 assert_eq!(error, Vec::new());
971 #[cfg(all(unix, not(target_os="android")))]
972 pub fn pwd_cmd() -> Command {
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");
983 pub fn pwd_cmd() -> Command {
984 let mut cmd = Command::new("cmd");
985 cmd.arg("/c").arg("cd");
990 fn test_keep_current_working_dir() {
992 let prog = pwd_cmd().spawn().unwrap();
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());
998 let parent_stat = parent_dir.stat().unwrap();
999 let child_stat = child_dir.stat().unwrap();
1001 assert_eq!(parent_stat.unstable.device, child_stat.unstable.device);
1002 assert_eq!(parent_stat.unstable.inode, child_stat.unstable.inode);
1006 fn test_change_working_directory() {
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();
1013 let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
1014 let child_dir = Path::new(output.trim());
1016 let parent_stat = parent_dir.stat().unwrap();
1017 let child_stat = child_dir.stat().unwrap();
1019 assert_eq!(parent_stat.unstable.device, child_stat.unstable.device);
1020 assert_eq!(parent_stat.unstable.inode, child_stat.unstable.inode);
1023 #[cfg(all(unix, not(target_os="android")))]
1024 pub fn env_cmd() -> Command {
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");
1035 pub fn env_cmd() -> Command {
1036 let mut cmd = Command::new("cmd");
1037 cmd.arg("/c").arg("set");
1041 #[cfg(not(target_os="android"))]
1043 fn test_inherit_env() {
1045 if running_on_valgrind() { return; }
1047 let prog = env_cmd().spawn().unwrap();
1048 let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
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{}",
1059 #[cfg(target_os="android")]
1061 fn test_inherit_env() {
1063 if running_on_valgrind() { return; }
1065 let mut prog = env_cmd().spawn().unwrap();
1066 let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
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!("{}={}",
1075 output.contains(format!("{}=\'{}\'",
1083 fn test_override_env() {
1085 let mut new_env = vec![("RUN_TEST_NEW_ENV", "123")];
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") {
1096 new_env.push(("PATH", path_val.as_slice()))
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();
1104 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1105 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
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();
1114 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1115 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1119 pub fn sleeper() -> Process {
1120 Command::new("sleep").arg("1000").spawn().unwrap()
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()
1132 let mut p = sleeper();
1133 Process::kill(p.id(), PleaseExitSignal).unwrap();
1134 assert!(!p.wait().unwrap().success());
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());
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());
1154 timer::sleep(Duration::milliseconds(100));
1156 panic!("never saw the child go away");
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());
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();
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();
1197 assert!(Process::kill(id, 0).is_ok());
1198 assert!(Process::kill(id, PleaseExitSignal).is_ok());
1202 fn dont_close_fd_on_command_spawn() {
1205 let path = if cfg!(windows) {
1208 Path::new("/dev/null")
1211 let fdes = match fs::open(&path, Truncate, Write) {
1213 Err(_) => panic!("failed to open file descriptor"),
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());
1224 fn env_map_keys_ci() {
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"));