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());
53 /// Take note that there is no implementation of
54 /// [`Drop`](../../core/ops/trait.Drop.html) for child processes, so if you
55 /// do not ensure the `Child` has exited then it will continue to run, even
56 /// after the `Child` handle to the child process has gone out of scope.
58 /// Calling `wait` (or other functions that wrap around it) will make the
59 /// parent process wait until the child has actually exited before continuing.
60 #[stable(feature = "process", since = "1.0.0")]
64 /// None until wait() or wait_with_output() is called.
65 status: Option<imp::ExitStatus>,
67 /// The handle for writing to the child's stdin, if it has been captured
68 #[stable(feature = "process", since = "1.0.0")]
69 pub stdin: Option<ChildStdin>,
71 /// The handle for reading from the child's stdout, if it has been captured
72 #[stable(feature = "process", since = "1.0.0")]
73 pub stdout: Option<ChildStdout>,
75 /// The handle for reading from the child's stderr, if it has been captured
76 #[stable(feature = "process", since = "1.0.0")]
77 pub stderr: Option<ChildStderr>,
80 impl AsInner<imp::Process> for Child {
81 fn as_inner(&self) -> &imp::Process { &self.handle }
84 impl IntoInner<imp::Process> for Child {
85 fn into_inner(self) -> imp::Process { self.handle }
88 /// A handle to a child process's stdin
89 #[stable(feature = "process", since = "1.0.0")]
90 pub struct ChildStdin {
94 #[stable(feature = "process", since = "1.0.0")]
95 impl Write for ChildStdin {
96 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
100 fn flush(&mut self) -> io::Result<()> {
105 impl AsInner<AnonPipe> for ChildStdin {
106 fn as_inner(&self) -> &AnonPipe { &self.inner }
109 impl IntoInner<AnonPipe> for ChildStdin {
110 fn into_inner(self) -> AnonPipe { self.inner }
113 /// A handle to a child process's stdout
114 #[stable(feature = "process", since = "1.0.0")]
115 pub struct ChildStdout {
119 #[stable(feature = "process", since = "1.0.0")]
120 impl Read for ChildStdout {
121 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
126 impl AsInner<AnonPipe> for ChildStdout {
127 fn as_inner(&self) -> &AnonPipe { &self.inner }
130 impl IntoInner<AnonPipe> for ChildStdout {
131 fn into_inner(self) -> AnonPipe { self.inner }
134 /// A handle to a child process's stderr
135 #[stable(feature = "process", since = "1.0.0")]
136 pub struct ChildStderr {
140 #[stable(feature = "process", since = "1.0.0")]
141 impl Read for ChildStderr {
142 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
147 impl AsInner<AnonPipe> for ChildStderr {
148 fn as_inner(&self) -> &AnonPipe { &self.inner }
151 impl IntoInner<AnonPipe> for ChildStderr {
152 fn into_inner(self) -> AnonPipe { self.inner }
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::process::Command;
164 /// let output = Command::new("sh")
166 /// .arg("echo hello")
168 /// .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
169 /// let hello = output.stdout;
171 #[stable(feature = "process", since = "1.0.0")]
175 // Details explained in the builder methods
176 stdin: Option<Stdio>,
177 stdout: Option<Stdio>,
178 stderr: Option<Stdio>,
182 /// Constructs a new `Command` for launching the program at
183 /// path `program`, with the following default configuration:
185 /// * No arguments to the program
186 /// * Inherit the current process's environment
187 /// * Inherit the current process's working directory
188 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
190 /// Builder methods are provided to change these defaults and
191 /// otherwise configure the process.
192 #[stable(feature = "process", since = "1.0.0")]
193 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
195 inner: imp::Command::new(program.as_ref()),
202 /// Add an argument to pass to the program.
203 #[stable(feature = "process", since = "1.0.0")]
204 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
205 self.inner.arg(arg.as_ref());
209 /// Add multiple arguments to pass to the program.
210 #[stable(feature = "process", since = "1.0.0")]
211 pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut Command {
212 self.inner.args(args.iter().map(AsRef::as_ref));
216 /// Inserts or updates an environment variable mapping.
218 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
219 /// and case-sensitive on all other platforms.
220 #[stable(feature = "process", since = "1.0.0")]
221 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
222 where K: AsRef<OsStr>, V: AsRef<OsStr>
224 self.inner.env(key.as_ref(), val.as_ref());
228 /// Removes an environment variable mapping.
229 #[stable(feature = "process", since = "1.0.0")]
230 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
231 self.inner.env_remove(key.as_ref());
235 /// Clears the entire environment map for the child process.
236 #[stable(feature = "process", since = "1.0.0")]
237 pub fn env_clear(&mut self) -> &mut Command {
238 self.inner.env_clear();
242 /// Sets the working directory for the child process.
243 #[stable(feature = "process", since = "1.0.0")]
244 pub fn current_dir<P: AsRef<path::Path>>(&mut self, dir: P) -> &mut Command {
245 self.inner.cwd(dir.as_ref().as_ref());
249 /// Configuration for the child process's stdin handle (file descriptor 0).
250 #[stable(feature = "process", since = "1.0.0")]
251 pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
252 self.stdin = Some(cfg);
256 /// Configuration for the child process's stdout handle (file descriptor 1).
257 #[stable(feature = "process", since = "1.0.0")]
258 pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
259 self.stdout = Some(cfg);
263 /// Configuration for the child process's stderr handle (file descriptor 2).
264 #[stable(feature = "process", since = "1.0.0")]
265 pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
266 self.stderr = Some(cfg);
270 fn spawn_inner(&self, default_io: StdioImp) -> io::Result<Child> {
271 let default_io = Stdio(default_io);
273 // See comment on `setup_io` for what `_drop_later` is.
274 let (their_stdin, our_stdin, _drop_later) = try!(
275 setup_io(self.stdin.as_ref().unwrap_or(&default_io), true)
277 let (their_stdout, our_stdout, _drop_later) = try!(
278 setup_io(self.stdout.as_ref().unwrap_or(&default_io), false)
280 let (their_stderr, our_stderr, _drop_later) = try!(
281 setup_io(self.stderr.as_ref().unwrap_or(&default_io), false)
284 match imp::Process::spawn(&self.inner, their_stdin, their_stdout,
287 Ok(handle) => Ok(Child {
290 stdin: our_stdin.map(|fd| ChildStdin { inner: fd }),
291 stdout: our_stdout.map(|fd| ChildStdout { inner: fd }),
292 stderr: our_stderr.map(|fd| ChildStderr { inner: fd }),
297 /// Executes the command as a child process, returning a handle to it.
299 /// By default, stdin, stdout and stderr are inherited from the parent.
300 #[stable(feature = "process", since = "1.0.0")]
301 pub fn spawn(&mut self) -> io::Result<Child> {
302 self.spawn_inner(StdioImp::Inherit)
305 /// Executes the command as a child process, waiting for it to finish and
306 /// collecting all of its output.
308 /// By default, stdin, stdout and stderr are captured (and used to
309 /// provide the resulting output).
314 /// use std::process::Command;
315 /// let output = Command::new("cat").arg("foo.txt").output().unwrap_or_else(|e| {
316 /// panic!("failed to execute process: {}", e)
319 /// println!("status: {}", output.status);
320 /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
321 /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
323 #[stable(feature = "process", since = "1.0.0")]
324 pub fn output(&mut self) -> io::Result<Output> {
325 self.spawn_inner(StdioImp::MakePipe).and_then(|p| p.wait_with_output())
328 /// Executes a command as a child process, waiting for it to finish and
329 /// collecting its exit status.
331 /// By default, stdin, stdout and stderr are inherited from the parent.
336 /// use std::process::Command;
338 /// let status = Command::new("ls").status().unwrap_or_else(|e| {
339 /// panic!("failed to execute process: {}", e)
342 /// println!("process exited with: {}", status);
344 #[stable(feature = "process", since = "1.0.0")]
345 pub fn status(&mut self) -> io::Result<ExitStatus> {
346 self.spawn().and_then(|mut p| p.wait())
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl fmt::Debug for Command {
352 /// Format the program and arguments of a Command for display. Any
353 /// non-utf8 data is lossily converted using the utf8 replacement
355 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
360 impl AsInner<imp::Command> for Command {
361 fn as_inner(&self) -> &imp::Command { &self.inner }
364 impl AsInnerMut<imp::Command> for Command {
365 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
368 // Takes a `Stdio` configuration (this module) and whether the to-be-owned
369 // handle will be readable.
371 // Returns a triple of (stdio to spawn with, stdio to store, stdio to drop). The
372 // stdio to spawn with is passed down to the `sys` module and indicates how the
373 // stdio stream should be set up. The "stdio to store" is an object which
374 // should be returned in the `Child` that makes its way out. The "stdio to drop"
375 // represents the raw value of "stdio to spawn with", but is the owned variant
376 // for it. This needs to be dropped after the child spawns
377 fn setup_io(io: &Stdio, readable: bool)
378 -> io::Result<(imp::Stdio, Option<AnonPipe>, Option<AnonPipe>)>
381 StdioImp::MakePipe => {
382 let (reader, writer) = try!(pipe::anon_pipe());
384 (imp::Stdio::Raw(reader.raw()), Some(writer), Some(reader))
386 (imp::Stdio::Raw(writer.raw()), Some(reader), Some(writer))
389 StdioImp::Raw(ref owned) => (imp::Stdio::Raw(owned.raw()), None, None),
390 StdioImp::Inherit => (imp::Stdio::Inherit, None, None),
391 StdioImp::None => (imp::Stdio::None, None, None),
395 /// The output of a finished process.
396 #[derive(PartialEq, Eq, Clone)]
397 #[stable(feature = "process", since = "1.0.0")]
399 /// The status (exit code) of the process.
400 #[stable(feature = "process", since = "1.0.0")]
401 pub status: ExitStatus,
402 /// The data that the process wrote to stdout.
403 #[stable(feature = "process", since = "1.0.0")]
405 /// The data that the process wrote to stderr.
406 #[stable(feature = "process", since = "1.0.0")]
410 // If either stderr or stdout are valid utf8 strings it prints the valid
411 // strings, otherwise it prints the byte sequence instead
412 #[stable(feature = "process_output_debug", since = "1.7.0")]
413 impl fmt::Debug for Output {
414 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
416 let stdout_utf8 = str::from_utf8(&self.stdout);
417 let stdout_debug: &fmt::Debug = match stdout_utf8 {
419 Err(_) => &self.stdout
422 let stderr_utf8 = str::from_utf8(&self.stderr);
423 let stderr_debug: &fmt::Debug = match stderr_utf8 {
425 Err(_) => &self.stderr
428 fmt.debug_struct("Output")
429 .field("status", &self.status)
430 .field("stdout", stdout_debug)
431 .field("stderr", stderr_debug)
436 /// Describes what to do with a standard I/O stream for a child process.
437 #[stable(feature = "process", since = "1.0.0")]
438 pub struct Stdio(StdioImp);
440 // The internal enum for stdio setup; see below for descriptions.
449 /// A new pipe should be arranged to connect the parent and child processes.
450 #[stable(feature = "process", since = "1.0.0")]
451 pub fn piped() -> Stdio { Stdio(StdioImp::MakePipe) }
453 /// The child inherits from the corresponding parent descriptor.
454 #[stable(feature = "process", since = "1.0.0")]
455 pub fn inherit() -> Stdio { Stdio(StdioImp::Inherit) }
457 /// This stream will be ignored. This is the equivalent of attaching the
458 /// stream to `/dev/null`
459 #[stable(feature = "process", since = "1.0.0")]
460 pub fn null() -> Stdio { Stdio(StdioImp::None) }
463 impl FromInner<imp::RawStdio> for Stdio {
464 fn from_inner(inner: imp::RawStdio) -> Stdio {
465 Stdio(StdioImp::Raw(inner))
469 /// Describes the result of a process after it has terminated.
470 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
471 #[stable(feature = "process", since = "1.0.0")]
472 pub struct ExitStatus(imp::ExitStatus);
475 /// Was termination successful? Signal termination not considered a success,
476 /// and success is defined as a zero exit status.
477 #[stable(feature = "process", since = "1.0.0")]
478 pub fn success(&self) -> bool {
482 /// Returns the exit code of the process, if any.
484 /// On Unix, this will return `None` if the process was terminated
485 /// by a signal; `std::os::unix` provides an extension trait for
486 /// extracting the signal and other details from the `ExitStatus`.
487 #[stable(feature = "process", since = "1.0.0")]
488 pub fn code(&self) -> Option<i32> {
493 impl AsInner<imp::ExitStatus> for ExitStatus {
494 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
497 #[stable(feature = "process", since = "1.0.0")]
498 impl fmt::Display for ExitStatus {
499 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
505 /// Forces the child to exit. This is equivalent to sending a
506 /// SIGKILL on unix platforms.
507 #[stable(feature = "process", since = "1.0.0")]
508 pub fn kill(&mut self) -> io::Result<()> {
509 #[cfg(unix)] fn collect_status(p: &mut Child) {
510 // On Linux (and possibly other unices), a process that has exited will
511 // continue to accept signals because it is "defunct". The delivery of
512 // signals will only fail once the child has been reaped. For this
513 // reason, if the process hasn't exited yet, then we attempt to collect
514 // their status with WNOHANG.
515 if p.status.is_none() {
516 match p.handle.try_wait() {
517 Some(status) => { p.status = Some(status); }
522 #[cfg(windows)] fn collect_status(_p: &mut Child) {}
524 collect_status(self);
526 // if the process has finished, and therefore had waitpid called,
527 // and we kill it, then on unix we might ending up killing a
528 // newer process that happens to have the same (re-used) id
529 if self.status.is_some() {
530 return Err(Error::new(
531 ErrorKind::InvalidInput,
532 "invalid argument: can't kill an exited process",
536 unsafe { self.handle.kill() }
539 /// Returns the OS-assigned process identifier associated with this child.
540 #[stable(feature = "process_id", since = "1.3.0")]
541 pub fn id(&self) -> u32 {
545 /// Waits for the child to exit completely, returning the status that it
546 /// exited with. This function will continue to have the same return value
547 /// after it has been called at least once.
549 /// The stdin handle to the child process, if any, will be closed
550 /// before waiting. This helps avoid deadlock: it ensures that the
551 /// child does not block waiting for input from the parent, while
552 /// the parent waits for the child to exit.
553 #[stable(feature = "process", since = "1.0.0")]
554 pub fn wait(&mut self) -> io::Result<ExitStatus> {
555 drop(self.stdin.take());
557 Some(code) => Ok(ExitStatus(code)),
559 let status = try!(self.handle.wait());
560 self.status = Some(status);
561 Ok(ExitStatus(status))
566 /// Simultaneously waits for the child to exit and collect all remaining
567 /// output on the stdout/stderr handles, returning an `Output`
570 /// The stdin handle to the child process, if any, will be closed
571 /// before waiting. This helps avoid deadlock: it ensures that the
572 /// child does not block waiting for input from the parent, while
573 /// the parent waits for the child to exit.
574 #[stable(feature = "process", since = "1.0.0")]
575 pub fn wait_with_output(mut self) -> io::Result<Output> {
576 drop(self.stdin.take());
577 fn read<R>(mut input: R) -> JoinHandle<io::Result<Vec<u8>>>
578 where R: Read + Send + 'static
580 thread::spawn(move || {
581 let mut ret = Vec::new();
582 input.read_to_end(&mut ret).map(|_| ret)
585 let stdout = self.stdout.take().map(read);
586 let stderr = self.stderr.take().map(read);
587 let status = try!(self.wait());
588 let stdout = stdout.and_then(|t| t.join().unwrap().ok());
589 let stderr = stderr.and_then(|t| t.join().unwrap().ok());
593 stdout: stdout.unwrap_or(Vec::new()),
594 stderr: stderr.unwrap_or(Vec::new()),
599 /// Terminates the current process with the specified exit code.
601 /// This function will never return and will immediately terminate the current
602 /// process. The exit code is passed through to the underlying OS and will be
603 /// available for consumption by another process.
605 /// Note that because this function never returns, and that it terminates the
606 /// process, no destructors on the current stack or any other thread's stack
607 /// will be run. If a clean shutdown is needed it is recommended to only call
608 /// this function at a known point where there are no more destructors left
610 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn exit(code: i32) -> ! {
612 ::sys_common::cleanup();
613 ::sys::os::exit(code)
623 use super::{Command, Output, Stdio};
625 // FIXME(#10380) these tests should not all be ignored on android.
628 #[cfg_attr(target_os = "android", ignore)]
630 let p = Command::new("true").spawn();
632 let mut p = p.unwrap();
633 assert!(p.wait().unwrap().success());
637 #[cfg_attr(target_os = "android", ignore)]
639 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
646 #[cfg_attr(target_os = "android", ignore)]
647 fn exit_reported_right() {
648 let p = Command::new("false").spawn();
650 let mut p = p.unwrap();
651 assert!(p.wait().unwrap().code() == Some(1));
657 #[cfg_attr(target_os = "android", ignore)]
658 fn signal_reported_right() {
659 use os::unix::process::ExitStatusExt;
661 let mut p = Command::new("/bin/sh")
662 .arg("-c").arg("read a")
663 .stdin(Stdio::piped())
666 match p.wait().unwrap().signal() {
668 result => panic!("not terminated by signal 9 (instead, {:?})",
673 pub fn run_output(mut cmd: Command) -> String {
676 let mut p = p.unwrap();
677 assert!(p.stdout.is_some());
678 let mut ret = String::new();
679 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
680 assert!(p.wait().unwrap().success());
685 #[cfg_attr(target_os = "android", ignore)]
687 let mut cmd = Command::new("echo");
688 cmd.arg("foobar").stdout(Stdio::piped());
689 assert_eq!(run_output(cmd), "foobar\n");
693 #[cfg_attr(any(windows, target_os = "android"), ignore)]
694 fn set_current_dir_works() {
695 let mut cmd = Command::new("/bin/sh");
696 cmd.arg("-c").arg("pwd")
698 .stdout(Stdio::piped());
699 assert_eq!(run_output(cmd), "/\n");
703 #[cfg_attr(any(windows, target_os = "android"), ignore)]
705 let mut p = Command::new("/bin/sh")
706 .arg("-c").arg("read line; echo $line")
707 .stdin(Stdio::piped())
708 .stdout(Stdio::piped())
710 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
711 drop(p.stdin.take());
712 let mut out = String::new();
713 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
714 assert!(p.wait().unwrap().success());
715 assert_eq!(out, "foobar\n");
720 #[cfg_attr(target_os = "android", ignore)]
723 use os::unix::prelude::*;
725 let mut p = Command::new("/bin/sh")
726 .arg("-c").arg("true")
727 .uid(unsafe { libc::getuid() })
728 .gid(unsafe { libc::getgid() })
730 assert!(p.wait().unwrap().success());
734 #[cfg_attr(target_os = "android", ignore)]
736 fn uid_to_root_fails() {
737 use os::unix::prelude::*;
740 // if we're already root, this isn't a valid test. Most of the bots run
741 // as non-root though (android is an exception).
742 if unsafe { libc::getuid() == 0 } { return }
743 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
747 #[cfg_attr(target_os = "android", ignore)]
748 fn test_process_status() {
749 let mut status = Command::new("false").status().unwrap();
750 assert!(status.code() == Some(1));
752 status = Command::new("true").status().unwrap();
753 assert!(status.success());
757 fn test_process_output_fail_to_start() {
758 match Command::new("/no-binary-by-this-name-should-exist").output() {
759 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
765 #[cfg_attr(target_os = "android", ignore)]
766 fn test_process_output_output() {
767 let Output {status, stdout, stderr}
768 = Command::new("echo").arg("hello").output().unwrap();
769 let output_str = str::from_utf8(&stdout).unwrap();
771 assert!(status.success());
772 assert_eq!(output_str.trim().to_string(), "hello");
773 assert_eq!(stderr, Vec::new());
777 #[cfg_attr(target_os = "android", ignore)]
778 fn test_process_output_error() {
779 let Output {status, stdout, stderr}
780 = Command::new("mkdir").arg(".").output().unwrap();
782 assert!(status.code() == Some(1));
783 assert_eq!(stdout, Vec::new());
784 assert!(!stderr.is_empty());
788 #[cfg_attr(target_os = "android", ignore)]
789 fn test_finish_once() {
790 let mut prog = Command::new("false").spawn().unwrap();
791 assert!(prog.wait().unwrap().code() == Some(1));
795 #[cfg_attr(target_os = "android", ignore)]
796 fn test_finish_twice() {
797 let mut prog = Command::new("false").spawn().unwrap();
798 assert!(prog.wait().unwrap().code() == Some(1));
799 assert!(prog.wait().unwrap().code() == Some(1));
803 #[cfg_attr(target_os = "android", ignore)]
804 fn test_wait_with_output_once() {
805 let prog = Command::new("echo").arg("hello").stdout(Stdio::piped())
807 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
808 let output_str = str::from_utf8(&stdout).unwrap();
810 assert!(status.success());
811 assert_eq!(output_str.trim().to_string(), "hello");
812 assert_eq!(stderr, Vec::new());
815 #[cfg(all(unix, not(target_os="android")))]
816 pub fn env_cmd() -> Command {
819 #[cfg(target_os="android")]
820 pub fn env_cmd() -> Command {
821 let mut cmd = Command::new("/system/bin/sh");
822 cmd.arg("-c").arg("set");
827 pub fn env_cmd() -> Command {
828 let mut cmd = Command::new("cmd");
829 cmd.arg("/c").arg("set");
834 fn test_inherit_env() {
837 let result = env_cmd().output().unwrap();
838 let output = String::from_utf8(result.stdout).unwrap();
840 for (ref k, ref v) in env::vars() {
841 // don't check android RANDOM variables
842 if cfg!(target_os = "android") && *k == "RANDOM" {
846 // Windows has hidden environment variables whose names start with
847 // equals signs (`=`). Those do not show up in the output of the
849 assert!((cfg!(windows) && k.starts_with("=")) ||
850 k.starts_with("DYLD") ||
851 output.contains(&format!("{}={}", *k, *v)) ||
852 output.contains(&format!("{}='{}'", *k, *v)),
853 "output doesn't contain `{}={}`\n{}",
859 fn test_override_env() {
862 // In some build environments (such as chrooted Nix builds), `env` can
863 // only be found in the explicitly-provided PATH env variable, not in
864 // default places such as /bin or /usr/bin. So we need to pass through
865 // PATH to our sub-process.
866 let mut cmd = env_cmd();
867 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
868 if let Some(p) = env::var_os("PATH") {
871 let result = cmd.output().unwrap();
872 let output = String::from_utf8_lossy(&result.stdout).to_string();
874 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
875 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
879 fn test_add_to_env() {
880 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
881 let output = String::from_utf8_lossy(&result.stdout).to_string();
883 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
884 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
887 // Regression tests for #30858.
889 fn test_interior_nul_in_progname_is_error() {
890 match Command::new("has-some-\0\0s-inside").spawn() {
891 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
897 fn test_interior_nul_in_arg_is_error() {
898 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
899 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
905 fn test_interior_nul_in_args_is_error() {
906 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
907 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
913 fn test_interior_nul_in_current_dir_is_error() {
914 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
915 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
920 // Regression tests for #30862.
922 fn test_interior_nul_in_env_key_is_error() {
923 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
924 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
930 fn test_interior_nul_in_env_value_is_error() {
931 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
932 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),