1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
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 //! Working with processes.
13 #![stable(feature = "process", since = "1.0.0")]
14 #![allow(non_upper_case_globals)]
21 use io::{self, Error, ErrorKind};
24 use sys::pipe::{self, AnonPipe};
25 use sys::process as imp;
26 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
27 use thread::{self, JoinHandle};
29 /// Representation of a running or exited child process.
31 /// This structure is used to represent and manage child processes. A child
32 /// process is created via the `Command` struct, which configures the spawning
33 /// process and can itself be constructed using a builder-style interface.
38 /// use std::process::Command;
40 /// let mut child = Command::new("/bin/cat")
43 /// .unwrap_or_else(|e| { panic!("failed to execute child: {}", e) });
45 /// let ecode = child.wait()
46 /// .unwrap_or_else(|e| { panic!("failed to wait on child: {}", e) });
48 /// assert!(ecode.success());
50 #[stable(feature = "process", since = "1.0.0")]
54 /// None until wait() or wait_with_output() is called.
55 status: Option<imp::ExitStatus>,
57 /// The handle for writing to the child's stdin, if it has been captured
58 #[stable(feature = "process", since = "1.0.0")]
59 pub stdin: Option<ChildStdin>,
61 /// The handle for reading from the child's stdout, if it has been captured
62 #[stable(feature = "process", since = "1.0.0")]
63 pub stdout: Option<ChildStdout>,
65 /// The handle for reading from the child's stderr, if it has been captured
66 #[stable(feature = "process", since = "1.0.0")]
67 pub stderr: Option<ChildStderr>,
70 impl AsInner<imp::Process> for Child {
71 fn as_inner(&self) -> &imp::Process { &self.handle }
74 impl IntoInner<imp::Process> for Child {
75 fn into_inner(self) -> imp::Process { self.handle }
78 /// A handle to a child process's stdin
79 #[stable(feature = "process", since = "1.0.0")]
80 pub struct ChildStdin {
84 #[stable(feature = "process", since = "1.0.0")]
85 impl Write for ChildStdin {
86 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
90 fn flush(&mut self) -> io::Result<()> {
95 impl AsInner<AnonPipe> for ChildStdin {
96 fn as_inner(&self) -> &AnonPipe { &self.inner }
99 impl IntoInner<AnonPipe> for ChildStdin {
100 fn into_inner(self) -> AnonPipe { self.inner }
103 /// A handle to a child process's stdout
104 #[stable(feature = "process", since = "1.0.0")]
105 pub struct ChildStdout {
109 #[stable(feature = "process", since = "1.0.0")]
110 impl Read for ChildStdout {
111 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
116 impl AsInner<AnonPipe> for ChildStdout {
117 fn as_inner(&self) -> &AnonPipe { &self.inner }
120 impl IntoInner<AnonPipe> for ChildStdout {
121 fn into_inner(self) -> AnonPipe { self.inner }
124 /// A handle to a child process's stderr
125 #[stable(feature = "process", since = "1.0.0")]
126 pub struct ChildStderr {
130 #[stable(feature = "process", since = "1.0.0")]
131 impl Read for ChildStderr {
132 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
137 impl AsInner<AnonPipe> for ChildStderr {
138 fn as_inner(&self) -> &AnonPipe { &self.inner }
141 impl IntoInner<AnonPipe> for ChildStderr {
142 fn into_inner(self) -> AnonPipe { self.inner }
145 /// The `Command` type acts as a process builder, providing fine-grained control
146 /// over how a new process should be spawned. A default configuration can be
147 /// generated using `Command::new(program)`, where `program` gives a path to the
148 /// program to be executed. Additional builder methods allow the configuration
149 /// to be changed (for example, by adding arguments) prior to spawning:
152 /// use std::process::Command;
154 /// let output = Command::new("sh")
156 /// .arg("echo hello")
158 /// .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
159 /// let hello = output.stdout;
161 #[stable(feature = "process", since = "1.0.0")]
165 // Details explained in the builder methods
166 stdin: Option<Stdio>,
167 stdout: Option<Stdio>,
168 stderr: Option<Stdio>,
172 /// Constructs a new `Command` for launching the program at
173 /// path `program`, with the following default configuration:
175 /// * No arguments to the program
176 /// * Inherit the current process's environment
177 /// * Inherit the current process's working directory
178 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
180 /// Builder methods are provided to change these defaults and
181 /// otherwise configure the process.
182 #[stable(feature = "process", since = "1.0.0")]
183 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
185 inner: imp::Command::new(program.as_ref()),
192 /// Add an argument to pass to the program.
193 #[stable(feature = "process", since = "1.0.0")]
194 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
195 self.inner.arg(arg.as_ref());
199 /// Add multiple arguments to pass to the program.
200 #[stable(feature = "process", since = "1.0.0")]
201 pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut Command {
202 self.inner.args(args.iter().map(AsRef::as_ref));
206 /// Inserts or updates an environment variable mapping.
208 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
209 /// and case-sensitive on all other platforms.
210 #[stable(feature = "process", since = "1.0.0")]
211 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
212 where K: AsRef<OsStr>, V: AsRef<OsStr>
214 self.inner.env(key.as_ref(), val.as_ref());
218 /// Removes an environment variable mapping.
219 #[stable(feature = "process", since = "1.0.0")]
220 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
221 self.inner.env_remove(key.as_ref());
225 /// Clears the entire environment map for the child process.
226 #[stable(feature = "process", since = "1.0.0")]
227 pub fn env_clear(&mut self) -> &mut Command {
228 self.inner.env_clear();
232 /// Sets the working directory for the child process.
233 #[stable(feature = "process", since = "1.0.0")]
234 pub fn current_dir<P: AsRef<path::Path>>(&mut self, dir: P) -> &mut Command {
235 self.inner.cwd(dir.as_ref().as_ref());
239 /// Configuration for the child process's stdin handle (file descriptor 0).
240 #[stable(feature = "process", since = "1.0.0")]
241 pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
242 self.stdin = Some(cfg);
246 /// Configuration for the child process's stdout handle (file descriptor 1).
247 #[stable(feature = "process", since = "1.0.0")]
248 pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
249 self.stdout = Some(cfg);
253 /// Configuration for the child process's stderr handle (file descriptor 2).
254 #[stable(feature = "process", since = "1.0.0")]
255 pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
256 self.stderr = Some(cfg);
260 fn spawn_inner(&self, default_io: StdioImp) -> io::Result<Child> {
261 let default_io = Stdio(default_io);
263 // See comment on `setup_io` for what `_drop_later` is.
264 let (their_stdin, our_stdin, _drop_later) = try!(
265 setup_io(self.stdin.as_ref().unwrap_or(&default_io), true)
267 let (their_stdout, our_stdout, _drop_later) = try!(
268 setup_io(self.stdout.as_ref().unwrap_or(&default_io), false)
270 let (their_stderr, our_stderr, _drop_later) = try!(
271 setup_io(self.stderr.as_ref().unwrap_or(&default_io), false)
274 match imp::Process::spawn(&self.inner, their_stdin, their_stdout,
277 Ok(handle) => Ok(Child {
280 stdin: our_stdin.map(|fd| ChildStdin { inner: fd }),
281 stdout: our_stdout.map(|fd| ChildStdout { inner: fd }),
282 stderr: our_stderr.map(|fd| ChildStderr { inner: fd }),
287 /// Executes the command as a child process, returning a handle to it.
289 /// By default, stdin, stdout and stderr are inherited from the parent.
290 #[stable(feature = "process", since = "1.0.0")]
291 pub fn spawn(&mut self) -> io::Result<Child> {
292 self.spawn_inner(StdioImp::Inherit)
295 /// Executes the command as a child process, waiting for it to finish and
296 /// collecting all of its output.
298 /// By default, stdin, stdout and stderr are captured (and used to
299 /// provide the resulting output).
304 /// use std::process::Command;
305 /// let output = Command::new("cat").arg("foo.txt").output().unwrap_or_else(|e| {
306 /// panic!("failed to execute process: {}", e)
309 /// println!("status: {}", output.status);
310 /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
311 /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
313 #[stable(feature = "process", since = "1.0.0")]
314 pub fn output(&mut self) -> io::Result<Output> {
315 self.spawn_inner(StdioImp::MakePipe).and_then(|p| p.wait_with_output())
318 /// Executes a command as a child process, waiting for it to finish and
319 /// collecting its exit status.
321 /// By default, stdin, stdout and stderr are inherited from the parent.
326 /// use std::process::Command;
328 /// let status = Command::new("ls").status().unwrap_or_else(|e| {
329 /// panic!("failed to execute process: {}", e)
332 /// println!("process exited with: {}", status);
334 #[stable(feature = "process", since = "1.0.0")]
335 pub fn status(&mut self) -> io::Result<ExitStatus> {
336 self.spawn().and_then(|mut p| p.wait())
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl fmt::Debug for Command {
342 /// Format the program and arguments of a Command for display. Any
343 /// non-utf8 data is lossily converted using the utf8 replacement
345 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
346 try!(write!(f, "{:?}", self.inner.program));
347 for arg in &self.inner.args {
348 try!(write!(f, " {:?}", arg));
354 impl AsInner<imp::Command> for Command {
355 fn as_inner(&self) -> &imp::Command { &self.inner }
358 impl AsInnerMut<imp::Command> for Command {
359 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
362 // Takes a `Stdio` configuration (this module) and whether the to-be-owned
363 // handle will be readable.
365 // Returns a triple of (stdio to spawn with, stdio to store, stdio to drop). The
366 // stdio to spawn with is passed down to the `sys` module and indicates how the
367 // stdio stream should be set up. The "stdio to store" is an object which
368 // should be returned in the `Child` that makes its way out. The "stdio to drop"
369 // represents the raw value of "stdio to spawn with", but is the owned variant
370 // for it. This needs to be dropped after the child spawns
371 fn setup_io(io: &Stdio, readable: bool)
372 -> io::Result<(imp::Stdio, Option<AnonPipe>, Option<AnonPipe>)>
375 StdioImp::MakePipe => {
376 let (reader, writer) = try!(pipe::anon_pipe());
378 (imp::Stdio::Raw(reader.raw()), Some(writer), Some(reader))
380 (imp::Stdio::Raw(writer.raw()), Some(reader), Some(writer))
383 StdioImp::Raw(ref owned) => (imp::Stdio::Raw(owned.raw()), None, None),
384 StdioImp::Inherit => (imp::Stdio::Inherit, None, None),
385 StdioImp::None => (imp::Stdio::None, None, None),
389 /// The output of a finished process.
390 #[derive(PartialEq, Eq, Clone)]
391 #[stable(feature = "process", since = "1.0.0")]
393 /// The status (exit code) of the process.
394 #[stable(feature = "process", since = "1.0.0")]
395 pub status: ExitStatus,
396 /// The data that the process wrote to stdout.
397 #[stable(feature = "process", since = "1.0.0")]
399 /// The data that the process wrote to stderr.
400 #[stable(feature = "process", since = "1.0.0")]
404 // If either stderr or stdout are valid utf8 strings it prints the valid
405 // strings, otherwise it prints the byte sequence instead
406 #[stable(feature = "process_output_debug", since = "1.7.0")]
407 impl fmt::Debug for Output {
408 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
410 let stdout_utf8 = str::from_utf8(&self.stdout);
411 let stdout_debug: &fmt::Debug = match stdout_utf8 {
413 Err(_) => &self.stdout
416 let stderr_utf8 = str::from_utf8(&self.stderr);
417 let stderr_debug: &fmt::Debug = match stderr_utf8 {
419 Err(_) => &self.stderr
422 fmt.debug_struct("Output")
423 .field("status", &self.status)
424 .field("stdout", stdout_debug)
425 .field("stderr", stderr_debug)
430 /// Describes what to do with a standard I/O stream for a child process.
431 #[stable(feature = "process", since = "1.0.0")]
432 pub struct Stdio(StdioImp);
434 // The internal enum for stdio setup; see below for descriptions.
443 /// A new pipe should be arranged to connect the parent and child processes.
444 #[stable(feature = "process", since = "1.0.0")]
445 pub fn piped() -> Stdio { Stdio(StdioImp::MakePipe) }
447 /// The child inherits from the corresponding parent descriptor.
448 #[stable(feature = "process", since = "1.0.0")]
449 pub fn inherit() -> Stdio { Stdio(StdioImp::Inherit) }
451 /// This stream will be ignored. This is the equivalent of attaching the
452 /// stream to `/dev/null`
453 #[stable(feature = "process", since = "1.0.0")]
454 pub fn null() -> Stdio { Stdio(StdioImp::None) }
457 impl FromInner<imp::RawStdio> for Stdio {
458 fn from_inner(inner: imp::RawStdio) -> Stdio {
459 Stdio(StdioImp::Raw(inner))
463 /// Describes the result of a process after it has terminated.
464 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
465 #[stable(feature = "process", since = "1.0.0")]
466 pub struct ExitStatus(imp::ExitStatus);
469 /// Was termination successful? Signal termination not considered a success,
470 /// and success is defined as a zero exit status.
471 #[stable(feature = "process", since = "1.0.0")]
472 pub fn success(&self) -> bool {
476 /// Returns the exit code of the process, if any.
478 /// On Unix, this will return `None` if the process was terminated
479 /// by a signal; `std::os::unix` provides an extension trait for
480 /// extracting the signal and other details from the `ExitStatus`.
481 #[stable(feature = "process", since = "1.0.0")]
482 pub fn code(&self) -> Option<i32> {
487 impl AsInner<imp::ExitStatus> for ExitStatus {
488 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
491 #[stable(feature = "process", since = "1.0.0")]
492 impl fmt::Display for ExitStatus {
493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
499 /// Forces the child to exit. This is equivalent to sending a
500 /// SIGKILL on unix platforms.
501 #[stable(feature = "process", since = "1.0.0")]
502 pub fn kill(&mut self) -> io::Result<()> {
503 #[cfg(unix)] fn collect_status(p: &mut Child) {
504 // On Linux (and possibly other unices), a process that has exited will
505 // continue to accept signals because it is "defunct". The delivery of
506 // signals will only fail once the child has been reaped. For this
507 // reason, if the process hasn't exited yet, then we attempt to collect
508 // their status with WNOHANG.
509 if p.status.is_none() {
510 match p.handle.try_wait() {
511 Some(status) => { p.status = Some(status); }
516 #[cfg(windows)] fn collect_status(_p: &mut Child) {}
518 collect_status(self);
520 // if the process has finished, and therefore had waitpid called,
521 // and we kill it, then on unix we might ending up killing a
522 // newer process that happens to have the same (re-used) id
523 if self.status.is_some() {
524 return Err(Error::new(
525 ErrorKind::InvalidInput,
526 "invalid argument: can't kill an exited process",
530 unsafe { self.handle.kill() }
533 /// Returns the OS-assigned process identifier associated with this child.
534 #[stable(feature = "process_id", since = "1.3.0")]
535 pub fn id(&self) -> u32 {
539 /// Waits for the child to exit completely, returning the status that it
540 /// exited with. This function will continue to have the same return value
541 /// after it has been called at least once.
543 /// The stdin handle to the child process, if any, will be closed
544 /// before waiting. This helps avoid deadlock: it ensures that the
545 /// child does not block waiting for input from the parent, while
546 /// the parent waits for the child to exit.
547 #[stable(feature = "process", since = "1.0.0")]
548 pub fn wait(&mut self) -> io::Result<ExitStatus> {
549 drop(self.stdin.take());
551 Some(code) => Ok(ExitStatus(code)),
553 let status = try!(self.handle.wait());
554 self.status = Some(status);
555 Ok(ExitStatus(status))
560 /// Simultaneously waits for the child to exit and collect all remaining
561 /// output on the stdout/stderr handles, returning an `Output`
564 /// The stdin handle to the child process, if any, will be closed
565 /// before waiting. This helps avoid deadlock: it ensures that the
566 /// child does not block waiting for input from the parent, while
567 /// the parent waits for the child to exit.
568 #[stable(feature = "process", since = "1.0.0")]
569 pub fn wait_with_output(mut self) -> io::Result<Output> {
570 drop(self.stdin.take());
571 fn read<R>(mut input: R) -> JoinHandle<io::Result<Vec<u8>>>
572 where R: Read + Send + 'static
574 thread::spawn(move || {
575 let mut ret = Vec::new();
576 input.read_to_end(&mut ret).map(|_| ret)
579 let stdout = self.stdout.take().map(read);
580 let stderr = self.stderr.take().map(read);
581 let status = try!(self.wait());
582 let stdout = stdout.and_then(|t| t.join().unwrap().ok());
583 let stderr = stderr.and_then(|t| t.join().unwrap().ok());
587 stdout: stdout.unwrap_or(Vec::new()),
588 stderr: stderr.unwrap_or(Vec::new()),
593 /// Terminates the current process with the specified exit code.
595 /// This function will never return and will immediately terminate the current
596 /// process. The exit code is passed through to the underlying OS and will be
597 /// available for consumption by another process.
599 /// Note that because this function never returns, and that it terminates the
600 /// process, no destructors on the current stack or any other thread's stack
601 /// will be run. If a clean shutdown is needed it is recommended to only call
602 /// this function at a known point where there are no more destructors left
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn exit(code: i32) -> ! {
606 ::sys_common::cleanup();
607 ::sys::os::exit(code)
617 use super::{Command, Output, Stdio};
619 // FIXME(#10380) these tests should not all be ignored on android.
622 #[cfg_attr(target_os = "android", ignore)]
624 let p = Command::new("true").spawn();
626 let mut p = p.unwrap();
627 assert!(p.wait().unwrap().success());
631 #[cfg_attr(target_os = "android", ignore)]
633 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
640 #[cfg_attr(target_os = "android", ignore)]
641 fn exit_reported_right() {
642 let p = Command::new("false").spawn();
644 let mut p = p.unwrap();
645 assert!(p.wait().unwrap().code() == Some(1));
651 #[cfg_attr(target_os = "android", ignore)]
652 fn signal_reported_right() {
653 use os::unix::process::ExitStatusExt;
655 let mut p = Command::new("/bin/sh")
656 .arg("-c").arg("read a")
657 .stdin(Stdio::piped())
660 match p.wait().unwrap().signal() {
662 result => panic!("not terminated by signal 9 (instead, {:?})",
667 pub fn run_output(mut cmd: Command) -> String {
670 let mut p = p.unwrap();
671 assert!(p.stdout.is_some());
672 let mut ret = String::new();
673 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
674 assert!(p.wait().unwrap().success());
679 #[cfg_attr(target_os = "android", ignore)]
681 let mut cmd = Command::new("echo");
682 cmd.arg("foobar").stdout(Stdio::piped());
683 assert_eq!(run_output(cmd), "foobar\n");
687 #[cfg_attr(any(windows, target_os = "android"), ignore)]
688 fn set_current_dir_works() {
689 let mut cmd = Command::new("/bin/sh");
690 cmd.arg("-c").arg("pwd")
692 .stdout(Stdio::piped());
693 assert_eq!(run_output(cmd), "/\n");
697 #[cfg_attr(any(windows, target_os = "android"), ignore)]
699 let mut p = Command::new("/bin/sh")
700 .arg("-c").arg("read line; echo $line")
701 .stdin(Stdio::piped())
702 .stdout(Stdio::piped())
704 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
705 drop(p.stdin.take());
706 let mut out = String::new();
707 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
708 assert!(p.wait().unwrap().success());
709 assert_eq!(out, "foobar\n");
714 #[cfg_attr(target_os = "android", ignore)]
717 use os::unix::prelude::*;
719 let mut p = Command::new("/bin/sh")
720 .arg("-c").arg("true")
721 .uid(unsafe { libc::getuid() })
722 .gid(unsafe { libc::getgid() })
724 assert!(p.wait().unwrap().success());
728 #[cfg_attr(target_os = "android", ignore)]
730 fn uid_to_root_fails() {
731 use os::unix::prelude::*;
734 // if we're already root, this isn't a valid test. Most of the bots run
735 // as non-root though (android is an exception).
736 if unsafe { libc::getuid() == 0 } { return }
737 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
741 #[cfg_attr(target_os = "android", ignore)]
742 fn test_process_status() {
743 let mut status = Command::new("false").status().unwrap();
744 assert!(status.code() == Some(1));
746 status = Command::new("true").status().unwrap();
747 assert!(status.success());
751 fn test_process_output_fail_to_start() {
752 match Command::new("/no-binary-by-this-name-should-exist").output() {
753 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
759 #[cfg_attr(target_os = "android", ignore)]
760 fn test_process_output_output() {
761 let Output {status, stdout, stderr}
762 = Command::new("echo").arg("hello").output().unwrap();
763 let output_str = str::from_utf8(&stdout).unwrap();
765 assert!(status.success());
766 assert_eq!(output_str.trim().to_string(), "hello");
767 assert_eq!(stderr, Vec::new());
771 #[cfg_attr(target_os = "android", ignore)]
772 fn test_process_output_error() {
773 let Output {status, stdout, stderr}
774 = Command::new("mkdir").arg(".").output().unwrap();
776 assert!(status.code() == Some(1));
777 assert_eq!(stdout, Vec::new());
778 assert!(!stderr.is_empty());
782 #[cfg_attr(target_os = "android", ignore)]
783 fn test_finish_once() {
784 let mut prog = Command::new("false").spawn().unwrap();
785 assert!(prog.wait().unwrap().code() == Some(1));
789 #[cfg_attr(target_os = "android", ignore)]
790 fn test_finish_twice() {
791 let mut prog = Command::new("false").spawn().unwrap();
792 assert!(prog.wait().unwrap().code() == Some(1));
793 assert!(prog.wait().unwrap().code() == Some(1));
797 #[cfg_attr(target_os = "android", ignore)]
798 fn test_wait_with_output_once() {
799 let prog = Command::new("echo").arg("hello").stdout(Stdio::piped())
801 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
802 let output_str = str::from_utf8(&stdout).unwrap();
804 assert!(status.success());
805 assert_eq!(output_str.trim().to_string(), "hello");
806 assert_eq!(stderr, Vec::new());
809 #[cfg(all(unix, not(target_os="android")))]
810 pub fn env_cmd() -> Command {
813 #[cfg(target_os="android")]
814 pub fn env_cmd() -> Command {
815 let mut cmd = Command::new("/system/bin/sh");
816 cmd.arg("-c").arg("set");
821 pub fn env_cmd() -> Command {
822 let mut cmd = Command::new("cmd");
823 cmd.arg("/c").arg("set");
828 fn test_inherit_env() {
831 let result = env_cmd().output().unwrap();
832 let output = String::from_utf8(result.stdout).unwrap();
834 for (ref k, ref v) in env::vars() {
835 // don't check android RANDOM variables
836 if cfg!(target_os = "android") && *k == "RANDOM" {
840 // Windows has hidden environment variables whose names start with
841 // equals signs (`=`). Those do not show up in the output of the
843 assert!((cfg!(windows) && k.starts_with("=")) ||
844 k.starts_with("DYLD") ||
845 output.contains(&format!("{}={}", *k, *v)) ||
846 output.contains(&format!("{}='{}'", *k, *v)),
847 "output doesn't contain `{}={}`\n{}",
853 fn test_override_env() {
856 // In some build environments (such as chrooted Nix builds), `env` can
857 // only be found in the explicitly-provided PATH env variable, not in
858 // default places such as /bin or /usr/bin. So we need to pass through
859 // PATH to our sub-process.
860 let mut cmd = env_cmd();
861 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
862 if let Some(p) = env::var_os("PATH") {
865 let result = cmd.output().unwrap();
866 let output = String::from_utf8_lossy(&result.stdout).to_string();
868 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
869 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
873 fn test_add_to_env() {
874 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
875 let output = String::from_utf8_lossy(&result.stdout).to_string();
877 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
878 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);