1 // Copyright 2012-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.
13 #[allow(missing_doc)];
18 use comm::{stream, SharedChan, GenericChan, GenericPort};
20 use libc::{pid_t, c_void, c_int};
22 use option::{Some, None};
27 use vec::ImmutableVector;
30 * A value representing a child process.
32 * The lifetime of this value is linked to the lifetime of the actual
33 * process - the Process destructor calls self.finish() which waits
34 * for the process to terminate.
38 /// The unique id of the process (this should never be negative).
42 * A handle to the process - on unix this will always be NULL, but on
43 * windows it will be a HANDLE to the process, which will prevent the
44 * pid being re-used until the handle is closed.
48 /// Some(fd), or None when stdin is being redirected from a fd not created by Process::new.
49 priv input: Option<c_int>,
51 /// Some(file), or None when stdout is being redirected to a fd not created by Process::new.
52 priv output: Option<*libc::FILE>,
54 /// Some(file), or None when stderr is being redirected to a fd not created by Process::new.
55 priv error: Option<*libc::FILE>,
57 /// None until finish() is called.
58 priv exit_code: Option<int>,
61 /// Options that can be given when starting a Process.
62 pub struct ProcessOptions<'self> {
65 * If this is None then the new process will have the same initial
66 * environment as the parent process.
68 * If this is Some(vec-of-names-and-values) then the new process will
69 * have an environment containing the given named values only.
71 env: Option<~[(~str, ~str)]>,
74 * If this is None then the new process will use the same initial working
75 * directory as the parent process.
77 * If this is Some(path) then the new process will use the given path
78 * for its initial working directory.
80 dir: Option<&'self Path>,
83 * If this is None then a new pipe will be created for the new process's
84 * input and Process.input() will provide a Writer to write to this pipe.
86 * If this is Some(file-descriptor) then the new process will read its input
87 * from the given file descriptor, Process.input_redirected() will return
88 * true, and Process.input() will fail.
93 * If this is None then a new pipe will be created for the new program's
94 * output and Process.output() will provide a Reader to read from this pipe.
96 * If this is Some(file-descriptor) then the new process will write its output
97 * to the given file descriptor, Process.output_redirected() will return
98 * true, and Process.output() will fail.
100 out_fd: Option<c_int>,
103 * If this is None then a new pipe will be created for the new program's
104 * error stream and Process.error() will provide a Reader to read from this pipe.
106 * If this is Some(file-descriptor) then the new process will write its error output
107 * to the given file descriptor, Process.error_redirected() will return true, and
108 * and Process.error() will fail.
110 err_fd: Option<c_int>,
113 impl <'self> ProcessOptions<'self> {
114 /// Return a ProcessOptions that has None in every field.
115 pub fn new<'a>() -> ProcessOptions<'a> {
126 /// The output of a finished process.
127 pub struct ProcessOutput {
129 /// The status (exit code) of the process.
132 /// The data that the process wrote to stdout.
135 /// The data that the process wrote to stderr.
141 * Spawns a new Process.
145 * * prog - The path to an executable.
146 * * args - Vector of arguments to pass to the child process.
147 * * options - Options to configure the environment of the process,
148 * the working directory and the standard IO streams.
150 pub fn new(prog: &str, args: &[~str],
151 options: ProcessOptions)
153 #[fixed_stack_segment]; #[inline(never)];
155 let (in_pipe, in_fd) = match options.in_fd {
157 let pipe = os::pipe();
158 (Some(pipe), pipe.input)
160 Some(fd) => (None, fd)
162 let (out_pipe, out_fd) = match options.out_fd {
164 let pipe = os::pipe();
165 (Some(pipe), pipe.out)
167 Some(fd) => (None, fd)
169 let (err_pipe, err_fd) = match options.err_fd {
171 let pipe = os::pipe();
172 (Some(pipe), pipe.out)
174 Some(fd) => (None, fd)
177 let res = spawn_process_os(prog, args, options.env.clone(), options.dir,
178 in_fd, out_fd, err_fd);
181 for pipe in in_pipe.iter() { libc::close(pipe.input); }
182 for pipe in out_pipe.iter() { libc::close(pipe.out); }
183 for pipe in err_pipe.iter() { libc::close(pipe.out); }
189 input: in_pipe.map(|pipe| pipe.out),
190 output: out_pipe.map(|pipe| os::fdopen(pipe.input)),
191 error: err_pipe.map(|pipe| os::fdopen(pipe.input)),
196 /// Returns the unique id of the process
197 pub fn get_id(&self) -> pid_t { self.pid }
199 fn input_fd(&mut self) -> c_int {
202 None => fail!("This Process's stdin was redirected to an \
203 existing file descriptor.")
207 fn output_file(&mut self) -> *libc::FILE {
210 None => fail!("This Process's stdout was redirected to an \
211 existing file descriptor.")
215 fn error_file(&mut self) -> *libc::FILE {
218 None => fail!("This Process's stderr was redirected to an \
219 existing file descriptor.")
224 * Returns whether this process is reading its stdin from an existing file
225 * descriptor rather than a pipe that was created specifically for this
228 * If this method returns true then self.input() will fail.
230 pub fn input_redirected(&self) -> bool {
235 * Returns whether this process is writing its stdout to an existing file
236 * descriptor rather than a pipe that was created specifically for this
239 * If this method returns true then self.output() will fail.
241 pub fn output_redirected(&self) -> bool {
242 self.output.is_none()
246 * Returns whether this process is writing its stderr to an existing file
247 * descriptor rather than a pipe that was created specifically for this
250 * If this method returns true then self.error() will fail.
252 pub fn error_redirected(&self) -> bool {
257 * Returns an io::Writer that can be used to write to this Process's stdin.
259 * Fails if this Process's stdin was redirected to an existing file descriptor.
261 pub fn input(&mut self) -> @io::Writer {
262 // FIXME: the Writer can still be used after self is destroyed: #2625
263 io::fd_writer(self.input_fd(), false)
267 * Returns an io::Reader that can be used to read from this Process's stdout.
269 * Fails if this Process's stdout was redirected to an existing file descriptor.
271 pub fn output(&mut self) -> @io::Reader {
272 // FIXME: the Reader can still be used after self is destroyed: #2625
273 io::FILE_reader(self.output_file(), false)
277 * Returns an io::Reader that can be used to read from this Process's stderr.
279 * Fails if this Process's stderr was redirected to an existing file descriptor.
281 pub fn error(&mut self) -> @io::Reader {
282 // FIXME: the Reader can still be used after self is destroyed: #2625
283 io::FILE_reader(self.error_file(), false)
287 * Closes the handle to the child process's stdin.
289 * If this process is reading its stdin from an existing file descriptor, then this
290 * method does nothing.
292 pub fn close_input(&mut self) {
293 #[fixed_stack_segment]; #[inline(never)];
295 Some(-1) | None => (),
300 self.input = Some(-1);
305 fn close_outputs(&mut self) {
306 #[fixed_stack_segment]; #[inline(never)];
307 fclose_and_null(&mut self.output);
308 fclose_and_null(&mut self.error);
310 fn fclose_and_null(f_opt: &mut Option<*libc::FILE>) {
311 #[allow(cstack)]; // fixed_stack_segment declared on enclosing fn
313 Some(f) if !f.is_null() => {
316 *f_opt = Some(0 as *libc::FILE);
325 * Closes the handle to stdin, waits for the child process to terminate,
326 * and returns the exit code.
328 * If the child has already been finished then the exit code is returned.
330 pub fn finish(&mut self) -> int {
331 for &code in self.exit_code.iter() {
335 let code = waitpid(self.pid);
336 self.exit_code = Some(code);
341 * Closes the handle to stdin, waits for the child process to terminate, and reads
342 * and returns all remaining output of stdout and stderr, along with the exit code.
344 * If the child has already been finished then the exit code and any remaining
345 * unread output of stdout and stderr will be returned.
347 * This method will fail if the child process's stdout or stderr streams were
348 * redirected to existing file descriptors.
350 pub fn finish_with_output(&mut self) -> ProcessOutput {
351 let output_file = self.output_file();
352 let error_file = self.error_file();
354 // Spawn two entire schedulers to read both stdout and sterr
355 // in parallel so we don't deadlock while blocking on one
356 // or the other. FIXME (#2625): Surely there's a much more
357 // clever way to do this.
358 let (p, ch) = stream();
359 let ch = SharedChan::new(ch);
360 let ch_clone = ch.clone();
361 do task::spawn_sched(task::SingleThreaded) {
362 let errput = io::FILE_reader(error_file, false);
363 ch.send((2, errput.read_whole_stream()));
365 do task::spawn_sched(task::SingleThreaded) {
366 let output = io::FILE_reader(output_file, false);
367 ch_clone.send((1, output.read_whole_stream()));
370 let status = self.finish();
372 let (errs, outs) = match (p.recv(), p.recv()) {
373 ((1, o), (2, e)) => (e, o),
374 ((2, e), (1, o)) => (e, o),
375 ((x, _), (y, _)) => {
376 fail!("unexpected file numbers: %u, %u", x, y);
380 return ProcessOutput {status: status,
385 fn destroy_internal(&mut self, force: bool) {
386 // if the process has finished, and therefore had waitpid called,
387 // and we kill it, then on unix we might ending up killing a
388 // newer process that happens to have the same (re-used) id
389 if self.exit_code.is_none() {
390 killpid(self.pid, force);
395 fn killpid(pid: pid_t, _force: bool) {
396 #[fixed_stack_segment]; #[inline(never)];
398 libc::funcs::extra::kernel32::TerminateProcess(
399 cast::transmute(pid), 1);
404 fn killpid(pid: pid_t, force: bool) {
405 #[fixed_stack_segment]; #[inline(never)];
407 let signal = if force {
408 libc::consts::os::posix88::SIGKILL
410 libc::consts::os::posix88::SIGTERM
414 libc::funcs::posix88::signal::kill(pid, signal as c_int);
420 * Terminates the process, giving it a chance to clean itself up if
421 * this is supported by the operating system.
423 * On Posix OSs SIGTERM will be sent to the process. On Win32
424 * TerminateProcess(..) will be called.
426 pub fn destroy(&mut self) { self.destroy_internal(false); }
429 * Terminates the process as soon as possible without giving it a
430 * chance to clean itself up.
432 * On Posix OSs SIGKILL will be sent to the process. On Win32
433 * TerminateProcess(..) will be called.
435 pub fn force_destroy(&mut self) { self.destroy_internal(true); }
438 impl Drop for Process {
440 // FIXME(#4330) Need self by value to get mutability.
441 let mut_self: &mut Process = unsafe { cast::transmute(self) };
444 mut_self.close_outputs();
445 free_handle(self.handle);
449 struct SpawnProcessResult {
455 fn spawn_process_os(prog: &str, args: &[~str],
456 env: Option<~[(~str, ~str)]>,
458 in_fd: c_int, out_fd: c_int, err_fd: c_int) -> SpawnProcessResult {
459 #[fixed_stack_segment]; #[inline(never)];
461 use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
462 use libc::consts::os::extra::{
464 STARTF_USESTDHANDLES,
465 INVALID_HANDLE_VALUE,
466 DUPLICATE_SAME_ACCESS
468 use libc::funcs::extra::kernel32::{
474 use libc::funcs::extra::msvcrt::get_osfhandle;
480 let mut si = zeroed_startupinfo();
481 si.cb = sys::size_of::<STARTUPINFO>() as DWORD;
482 si.dwFlags = STARTF_USESTDHANDLES;
484 let cur_proc = GetCurrentProcess();
486 let orig_std_in = get_osfhandle(in_fd) as HANDLE;
487 if orig_std_in == INVALID_HANDLE_VALUE as HANDLE {
488 fail!("failure in get_osfhandle: %s", os::last_os_error());
490 if DuplicateHandle(cur_proc, orig_std_in, cur_proc, &mut si.hStdInput,
491 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
492 fail!("failure in DuplicateHandle: %s", os::last_os_error());
495 let orig_std_out = get_osfhandle(out_fd) as HANDLE;
496 if orig_std_out == INVALID_HANDLE_VALUE as HANDLE {
497 fail!("failure in get_osfhandle: %s", os::last_os_error());
499 if DuplicateHandle(cur_proc, orig_std_out, cur_proc, &mut si.hStdOutput,
500 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
501 fail!("failure in DuplicateHandle: %s", os::last_os_error());
504 let orig_std_err = get_osfhandle(err_fd) as HANDLE;
505 if orig_std_err == INVALID_HANDLE_VALUE as HANDLE {
506 fail!("failure in get_osfhandle: %s", os::last_os_error());
508 if DuplicateHandle(cur_proc, orig_std_err, cur_proc, &mut si.hStdError,
509 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
510 fail!("failure in DuplicateHandle: %s", os::last_os_error());
513 let cmd = make_command_line(prog, args);
514 let mut pi = zeroed_process_information();
515 let mut create_err = None;
517 do with_envp(env) |envp| {
518 do with_dirp(dir) |dirp| {
519 do cmd.with_c_str |cmdp| {
520 let created = CreateProcessA(ptr::null(), cast::transmute(cmdp),
521 ptr::mut_null(), ptr::mut_null(), TRUE,
522 0, envp, dirp, &mut si, &mut pi);
523 if created == FALSE {
524 create_err = Some(os::last_os_error());
530 CloseHandle(si.hStdInput);
531 CloseHandle(si.hStdOutput);
532 CloseHandle(si.hStdError);
534 for msg in create_err.iter() {
535 fail!("failure in CreateProcess: %s", *msg);
538 // We close the thread handle because we don't care about keeping the thread id valid,
539 // and we aren't keeping the thread handle around to be able to close it later. We don't
540 // close the process handle however because we want the process id to stay valid at least
541 // until the calling code closes the process handle.
542 CloseHandle(pi.hThread);
545 pid: pi.dwProcessId as pid_t,
546 handle: pi.hProcess as *()
552 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
553 libc::types::os::arch::extra::STARTUPINFO {
555 lpReserved: ptr::mut_null(),
556 lpDesktop: ptr::mut_null(),
557 lpTitle: ptr::mut_null(),
568 lpReserved2: ptr::mut_null(),
569 hStdInput: ptr::mut_null(),
570 hStdOutput: ptr::mut_null(),
571 hStdError: ptr::mut_null()
576 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
577 libc::types::os::arch::extra::PROCESS_INFORMATION {
578 hProcess: ptr::mut_null(),
579 hThread: ptr::mut_null(),
585 // FIXME: this is only pub so it can be tested (see issue #4536)
587 pub fn make_command_line(prog: &str, args: &[~str]) -> ~str {
589 append_arg(&mut cmd, prog);
590 for arg in args.iter() {
592 append_arg(&mut cmd, *arg);
596 fn append_arg(cmd: &mut ~str, arg: &str) {
597 let quote = arg.iter().any(|c| c == ' ' || c == '\t');
601 for i in range(0u, arg.len()) {
602 append_char_at(cmd, arg, i);
609 fn append_char_at(cmd: &mut ~str, arg: &str, i: uint) {
610 match arg[i] as char {
613 cmd.push_str("\\\"");
616 if backslash_run_ends_in_quote(arg, i) {
617 // Double all backslashes that are in runs before quotes.
618 cmd.push_str("\\\\");
620 // Pass other backslashes through unescaped.
630 fn backslash_run_ends_in_quote(s: &str, mut i: uint) -> bool {
631 while i < s.len() && s[i] as char == '\\' {
634 return i < s.len() && s[i] as char == '"';
639 fn spawn_process_os(prog: &str, args: &[~str],
640 env: Option<~[(~str, ~str)]>,
642 in_fd: c_int, out_fd: c_int, err_fd: c_int) -> SpawnProcessResult {
643 #[fixed_stack_segment]; #[inline(never)];
645 use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
646 use libc::funcs::bsd44::getdtablesize;
653 pub fn rust_unset_sigprocmask();
654 pub fn rust_set_environ(envp: *c_void);
662 fail!("failure in fork: %s", os::last_os_error());
664 return SpawnProcessResult {pid: pid, handle: ptr::null()};
667 rustrt::rust_unset_sigprocmask();
669 if dup2(in_fd, 0) == -1 {
670 fail!("failure in dup2(in_fd, 0): %s", os::last_os_error());
672 if dup2(out_fd, 1) == -1 {
673 fail!("failure in dup2(out_fd, 1): %s", os::last_os_error());
675 if dup2(err_fd, 2) == -1 {
676 fail!("failure in dup3(err_fd, 2): %s", os::last_os_error());
678 // close all other fds
679 for fd in range(3, getdtablesize()).invert() {
683 do with_dirp(dir) |dirp| {
684 if !dirp.is_null() && chdir(dirp) == -1 {
685 fail!("failure in chdir: %s", os::last_os_error());
689 do with_envp(env) |envp| {
691 rustrt::rust_set_environ(envp);
693 do with_argv(prog, args) |argv| {
695 // execvp only returns if an error occurred
696 fail!("failure in execvp: %s", os::last_os_error());
703 fn with_argv<T>(prog: &str, args: &[~str], cb: &fn(**libc::c_char) -> T) -> T {
706 // We can't directly convert `str`s into `*char`s, as someone needs to hold
707 // a reference to the intermediary byte buffers. So first build an array to
708 // hold all the ~[u8] byte strings.
709 let mut tmps = vec::with_capacity(args.len() + 1);
711 tmps.push(prog.to_c_str());
713 for arg in args.iter() {
714 tmps.push(arg.to_c_str());
717 // Next, convert each of the byte strings into a pointer. This is
718 // technically unsafe as the caller could leak these pointers out of our
720 let mut ptrs = do tmps.map |tmp| {
721 tmp.with_ref(|buf| buf)
724 // Finally, make sure we add a null pointer.
725 ptrs.push(ptr::null());
727 ptrs.as_imm_buf(|buf, _| cb(buf))
731 fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: &fn(*c_void) -> T) -> T {
734 // On posixy systems we can pass a char** for envp, which is a
735 // null-terminated array of "k=v\n" strings. Like `with_argv`, we have to
736 // have a temporary buffer to hold the intermediary `~[u8]` byte strings.
739 let mut tmps = vec::with_capacity(env.len());
741 for pair in env.iter() {
742 // Use of match here is just to workaround limitations
743 // in the stage0 irrefutable pattern impl.
744 let kv = fmt!("%s=%s", pair.first(), pair.second());
745 tmps.push(kv.to_c_str());
748 // Once again, this is unsafe.
749 let mut ptrs = do tmps.map |tmp| {
750 tmp.with_ref(|buf| buf)
752 ptrs.push(ptr::null());
754 do ptrs.as_imm_buf |buf, _| {
755 unsafe { cb(cast::transmute(buf)) }
763 fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: &fn(*mut c_void) -> T) -> T {
764 // On win32 we pass an "environment block" which is not a char**, but
765 // rather a concatenation of null-terminated k=v\0 sequences, with a final
771 for pair in env.iter() {
772 let kv = fmt!("%s=%s", pair.first(), pair.second());
773 blk.push_all(kv.as_bytes());
779 do blk.as_imm_buf |p, _len| {
780 unsafe { cb(cast::transmute(p)) }
783 _ => cb(ptr::mut_null())
787 fn with_dirp<T>(d: Option<&Path>, cb: &fn(*libc::c_char) -> T) -> T {
789 Some(dir) => dir.with_c_str(|buf| cb(buf)),
790 None => cb(ptr::null())
795 fn free_handle(handle: *()) {
796 #[fixed_stack_segment]; #[inline(never)];
798 libc::funcs::extra::kernel32::CloseHandle(cast::transmute(handle));
803 fn free_handle(_handle: *()) {
804 // unix has no process handle object, just a pid
808 * Spawns a process and waits for it to terminate. The process will
809 * inherit the current stdin/stdout/stderr file descriptors.
813 * * prog - The path to an executable
814 * * args - Vector of arguments to pass to the child process
818 * The process's exit code
820 pub fn process_status(prog: &str, args: &[~str]) -> int {
821 let mut prog = Process::new(prog, args, ProcessOptions {
832 * Spawns a process, records all its output, and waits for it to terminate.
836 * * prog - The path to an executable
837 * * args - Vector of arguments to pass to the child process
841 * The process's stdout/stderr output and exit code.
843 pub fn process_output(prog: &str, args: &[~str]) -> ProcessOutput {
844 let mut prog = Process::new(prog, args, ProcessOptions::new());
845 prog.finish_with_output()
849 * Waits for a process to exit and returns the exit code, failing
850 * if there is no process with the specified id.
852 * Note that this is private to avoid race conditions on unix where if
853 * a user calls waitpid(some_process.get_id()) then some_process.finish()
854 * and some_process.destroy() and some_process.finalize() will then either
855 * operate on a none-existent process or, even worse, on a newer process
858 fn waitpid(pid: pid_t) -> int {
859 return waitpid_os(pid);
862 fn waitpid_os(pid: pid_t) -> int {
863 #[fixed_stack_segment]; #[inline(never)];
865 use libc::types::os::arch::extra::DWORD;
866 use libc::consts::os::extra::{
868 PROCESS_QUERY_INFORMATION,
874 use libc::funcs::extra::kernel32::{
883 let proc = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE, pid as DWORD);
885 fail!("failure in OpenProcess: %s", os::last_os_error());
890 if GetExitCodeProcess(proc, &mut status) == FALSE {
892 fail!("failure in GetExitCodeProcess: %s", os::last_os_error());
894 if status != STILL_ACTIVE {
896 return status as int;
898 if WaitForSingleObject(proc, INFINITE) == WAIT_FAILED {
900 fail!("failure in WaitForSingleObject: %s", os::last_os_error());
907 fn waitpid_os(pid: pid_t) -> int {
908 #[fixed_stack_segment]; #[inline(never)];
910 use libc::funcs::posix01::wait::*;
912 #[cfg(target_os = "linux")]
913 #[cfg(target_os = "android")]
914 fn WIFEXITED(status: i32) -> bool {
915 (status & 0xffi32) == 0i32
918 #[cfg(target_os = "macos")]
919 #[cfg(target_os = "freebsd")]
920 fn WIFEXITED(status: i32) -> bool {
921 (status & 0x7fi32) == 0i32
924 #[cfg(target_os = "linux")]
925 #[cfg(target_os = "android")]
926 fn WEXITSTATUS(status: i32) -> i32 {
927 (status >> 8i32) & 0xffi32
930 #[cfg(target_os = "macos")]
931 #[cfg(target_os = "freebsd")]
932 fn WEXITSTATUS(status: i32) -> i32 {
936 let mut status = 0 as c_int;
937 if unsafe { waitpid(pid, &mut status, 0) } == -1 {
938 fail!("failure in waitpid: %s", os::last_os_error());
941 return if WIFEXITED(status) {
942 WEXITSTATUS(status) as int
953 use option::{Option, None, Some};
958 use unstable::running_on_valgrind;
962 fn test_make_command_line() {
964 run::make_command_line("prog", [~"aaa", ~"bbb", ~"ccc"]),
968 run::make_command_line("C:\\Program Files\\blah\\blah.exe", [~"aaa"]),
969 ~"\"C:\\Program Files\\blah\\blah.exe\" aaa"
972 run::make_command_line("C:\\Program Files\\test", [~"aa\"bb"]),
973 ~"\"C:\\Program Files\\test\" aa\\\"bb"
976 run::make_command_line("echo", [~"a b c"]),
982 #[cfg(not(target_os="android"))]
983 fn test_process_status() {
984 assert_eq!(run::process_status("false", []), 1);
985 assert_eq!(run::process_status("true", []), 0);
988 #[cfg(target_os="android")]
989 fn test_process_status() {
990 assert_eq!(run::process_status("/system/bin/sh", [~"-c",~"false"]), 1);
991 assert_eq!(run::process_status("/system/bin/sh", [~"-c",~"true"]), 0);
995 #[cfg(not(target_os="android"))]
996 fn test_process_output_output() {
998 let run::ProcessOutput {status, output, error}
999 = run::process_output("echo", [~"hello"]);
1000 let output_str = str::from_bytes(output);
1002 assert_eq!(status, 0);
1003 assert_eq!(output_str.trim().to_owned(), ~"hello");
1005 if !running_on_valgrind() {
1006 assert_eq!(error, ~[]);
1010 #[cfg(target_os="android")]
1011 fn test_process_output_output() {
1013 let run::ProcessOutput {status, output, error}
1014 = run::process_output("/system/bin/sh", [~"-c",~"echo hello"]);
1015 let output_str = str::from_bytes(output);
1017 assert_eq!(status, 0);
1018 assert_eq!(output_str.trim().to_owned(), ~"hello");
1020 if !running_on_valgrind() {
1021 assert_eq!(error, ~[]);
1026 #[cfg(not(target_os="android"))]
1027 fn test_process_output_error() {
1029 let run::ProcessOutput {status, output, error}
1030 = run::process_output("mkdir", [~"."]);
1032 assert_eq!(status, 1);
1033 assert_eq!(output, ~[]);
1034 assert!(!error.is_empty());
1037 #[cfg(target_os="android")]
1038 fn test_process_output_error() {
1040 let run::ProcessOutput {status, output, error}
1041 = run::process_output("/system/bin/mkdir", [~"."]);
1043 assert_eq!(status, 255);
1044 assert_eq!(output, ~[]);
1045 assert!(!error.is_empty());
1051 let pipe_in = os::pipe();
1052 let pipe_out = os::pipe();
1053 let pipe_err = os::pipe();
1055 let mut proc = run::Process::new("cat", [], run::ProcessOptions {
1058 in_fd: Some(pipe_in.input),
1059 out_fd: Some(pipe_out.out),
1060 err_fd: Some(pipe_err.out)
1063 assert!(proc.input_redirected());
1064 assert!(proc.output_redirected());
1065 assert!(proc.error_redirected());
1067 os::close(pipe_in.input);
1068 os::close(pipe_out.out);
1069 os::close(pipe_err.out);
1071 let expected = ~"test";
1072 writeclose(pipe_in.out, expected);
1073 let actual = readclose(pipe_out.input);
1074 readclose(pipe_err.input);
1077 assert_eq!(expected, actual);
1080 fn writeclose(fd: c_int, s: &str) {
1081 let writer = io::fd_writer(fd, false);
1082 writer.write_str(s);
1086 fn readclose(fd: c_int) -> ~str {
1087 #[fixed_stack_segment]; #[inline(never)];
1090 let file = os::fdopen(fd);
1091 let reader = io::FILE_reader(file, false);
1092 let buf = reader.read_whole_stream();
1094 str::from_bytes(buf)
1099 #[cfg(not(target_os="android"))]
1100 fn test_finish_once() {
1101 let mut prog = run::Process::new("false", [], run::ProcessOptions::new());
1102 assert_eq!(prog.finish(), 1);
1105 #[cfg(target_os="android")]
1106 fn test_finish_once() {
1107 let mut prog = run::Process::new("/system/bin/sh", [~"-c",~"false"],
1108 run::ProcessOptions::new());
1109 assert_eq!(prog.finish(), 1);
1113 #[cfg(not(target_os="android"))]
1114 fn test_finish_twice() {
1115 let mut prog = run::Process::new("false", [], run::ProcessOptions::new());
1116 assert_eq!(prog.finish(), 1);
1117 assert_eq!(prog.finish(), 1);
1120 #[cfg(target_os="android")]
1121 fn test_finish_twice() {
1122 let mut prog = run::Process::new("/system/bin/sh", [~"-c",~"false"],
1123 run::ProcessOptions::new());
1124 assert_eq!(prog.finish(), 1);
1125 assert_eq!(prog.finish(), 1);
1129 #[cfg(not(target_os="android"))]
1130 fn test_finish_with_output_once() {
1132 let mut prog = run::Process::new("echo", [~"hello"], run::ProcessOptions::new());
1133 let run::ProcessOutput {status, output, error}
1134 = prog.finish_with_output();
1135 let output_str = str::from_bytes(output);
1137 assert_eq!(status, 0);
1138 assert_eq!(output_str.trim().to_owned(), ~"hello");
1140 if !running_on_valgrind() {
1141 assert_eq!(error, ~[]);
1145 #[cfg(target_os="android")]
1146 fn test_finish_with_output_once() {
1148 let mut prog = run::Process::new("/system/bin/sh", [~"-c",~"echo hello"],
1149 run::ProcessOptions::new());
1150 let run::ProcessOutput {status, output, error}
1151 = prog.finish_with_output();
1152 let output_str = str::from_bytes(output);
1154 assert_eq!(status, 0);
1155 assert_eq!(output_str.trim().to_owned(), ~"hello");
1157 if !running_on_valgrind() {
1158 assert_eq!(error, ~[]);
1163 #[cfg(not(target_os="android"))]
1164 fn test_finish_with_output_twice() {
1166 let mut prog = run::Process::new("echo", [~"hello"], run::ProcessOptions::new());
1167 let run::ProcessOutput {status, output, error}
1168 = prog.finish_with_output();
1170 let output_str = str::from_bytes(output);
1172 assert_eq!(status, 0);
1173 assert_eq!(output_str.trim().to_owned(), ~"hello");
1175 if !running_on_valgrind() {
1176 assert_eq!(error, ~[]);
1179 let run::ProcessOutput {status, output, error}
1180 = prog.finish_with_output();
1182 assert_eq!(status, 0);
1183 assert_eq!(output, ~[]);
1185 if !running_on_valgrind() {
1186 assert_eq!(error, ~[]);
1190 #[cfg(target_os="android")]
1191 fn test_finish_with_output_twice() {
1193 let mut prog = run::Process::new("/system/bin/sh", [~"-c",~"echo hello"],
1194 run::ProcessOptions::new());
1195 let run::ProcessOutput {status, output, error}
1196 = prog.finish_with_output();
1198 let output_str = str::from_bytes(output);
1200 assert_eq!(status, 0);
1201 assert_eq!(output_str.trim().to_owned(), ~"hello");
1203 if !running_on_valgrind() {
1204 assert_eq!(error, ~[]);
1207 let run::ProcessOutput {status, output, error}
1208 = prog.finish_with_output();
1210 assert_eq!(status, 0);
1211 assert_eq!(output, ~[]);
1213 if !running_on_valgrind() {
1214 assert_eq!(error, ~[]);
1220 #[cfg(not(windows),not(target_os="android"))]
1221 fn test_finish_with_output_redirected() {
1222 let mut prog = run::Process::new("echo", [~"hello"], run::ProcessOptions {
1229 // this should fail because it is not valid to read the output when it was redirected
1230 prog.finish_with_output();
1234 #[cfg(not(windows),target_os="android")]
1235 fn test_finish_with_output_redirected() {
1236 let mut prog = run::Process::new("/system/bin/sh", [~"-c",~"echo hello"],
1237 run::ProcessOptions {
1244 // this should fail because it is not valid to read the output when it was redirected
1245 prog.finish_with_output();
1248 #[cfg(unix,not(target_os="android"))]
1249 fn run_pwd(dir: Option<&Path>) -> run::Process {
1250 run::Process::new("pwd", [], run::ProcessOptions {
1252 .. run::ProcessOptions::new()
1255 #[cfg(unix,target_os="android")]
1256 fn run_pwd(dir: Option<&Path>) -> run::Process {
1257 run::Process::new("/system/bin/sh", [~"-c",~"pwd"], run::ProcessOptions {
1259 .. run::ProcessOptions::new()
1264 fn run_pwd(dir: Option<&Path>) -> run::Process {
1265 run::Process::new("cmd", [~"/c", ~"cd"], run::ProcessOptions {
1267 .. run::ProcessOptions::new()
1272 fn test_keep_current_working_dir() {
1273 let mut prog = run_pwd(None);
1275 let output = str::from_bytes(prog.finish_with_output().output);
1276 let parent_dir = os::getcwd().normalize();
1277 let child_dir = Path(output.trim()).normalize();
1279 let parent_stat = parent_dir.stat().unwrap();
1280 let child_stat = child_dir.stat().unwrap();
1282 assert_eq!(parent_stat.st_dev, child_stat.st_dev);
1283 assert_eq!(parent_stat.st_ino, child_stat.st_ino);
1287 fn test_change_working_directory() {
1288 // test changing to the parent of os::getcwd() because we know
1289 // the path exists (and os::getcwd() is not expected to be root)
1290 let parent_dir = os::getcwd().dir_path().normalize();
1291 let mut prog = run_pwd(Some(&parent_dir));
1293 let output = str::from_bytes(prog.finish_with_output().output);
1294 let child_dir = Path(output.trim()).normalize();
1296 let parent_stat = parent_dir.stat().unwrap();
1297 let child_stat = child_dir.stat().unwrap();
1299 assert_eq!(parent_stat.st_dev, child_stat.st_dev);
1300 assert_eq!(parent_stat.st_ino, child_stat.st_ino);
1303 #[cfg(unix,not(target_os="android"))]
1304 fn run_env(env: Option<~[(~str, ~str)]>) -> run::Process {
1305 run::Process::new("env", [], run::ProcessOptions {
1307 .. run::ProcessOptions::new()
1310 #[cfg(unix,target_os="android")]
1311 fn run_env(env: Option<~[(~str, ~str)]>) -> run::Process {
1312 run::Process::new("/system/bin/sh", [~"-c",~"set"], run::ProcessOptions {
1314 .. run::ProcessOptions::new()
1319 fn run_env(env: Option<~[(~str, ~str)]>) -> run::Process {
1320 run::Process::new("cmd", [~"/c", ~"set"], run::ProcessOptions {
1322 .. run::ProcessOptions::new()
1327 #[cfg(not(target_os="android"))]
1328 fn test_inherit_env() {
1329 if running_on_valgrind() { return; }
1331 let mut prog = run_env(None);
1332 let output = str::from_bytes(prog.finish_with_output().output);
1335 for &(ref k, ref v) in r.iter() {
1336 // don't check windows magical empty-named variables
1337 assert!(k.is_empty() || output.contains(fmt!("%s=%s", *k, *v)));
1341 #[cfg(target_os="android")]
1342 fn test_inherit_env() {
1343 if running_on_valgrind() { return; }
1345 let mut prog = run_env(None);
1346 let output = str::from_bytes(prog.finish_with_output().output);
1349 for &(ref k, ref v) in r.iter() {
1350 // don't check android RANDOM variables
1351 if *k != ~"RANDOM" {
1352 assert!(output.contains(fmt!("%s=%s", *k, *v)) ||
1353 output.contains(fmt!("%s=\'%s\'", *k, *v)));
1359 fn test_add_to_env() {
1361 let mut new_env = os::env();
1362 new_env.push((~"RUN_TEST_NEW_ENV", ~"123"));
1364 let mut prog = run_env(Some(new_env));
1365 let output = str::from_bytes(prog.finish_with_output().output);
1367 assert!(output.contains("RUN_TEST_NEW_ENV=123"));