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 //! A module for working with processes.
15 //! Basic usage where we try to execute the `cat` shell command:
18 //! use std::process::Command;
20 //! let mut child = Command::new("/bin/cat")
23 //! .expect("failed to execute child");
25 //! let ecode = child.wait()
26 //! .expect("failed to wait on child");
28 //! assert!(ecode.success());
31 //! Calling a command with input and reading its output:
34 //! use std::process::{Command, Stdio};
35 //! use std::io::Write;
37 //! let mut child = Command::new("/bin/cat")
38 //! .stdin(Stdio::piped())
39 //! .stdout(Stdio::piped())
41 //! .expect("failed to execute child");
44 //! // limited borrow of stdin
45 //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
46 //! stdin.write_all(b"test").expect("failed to write to stdin");
49 //! let output = child
50 //! .wait_with_output()
51 //! .expect("failed to wait on child");
53 //! assert_eq!(b"test", output.stdout.as_slice());
56 #![stable(feature = "process", since = "1.0.0")]
65 use sys::pipe::{read2, AnonPipe};
66 use sys::process as imp;
67 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
69 /// Representation of a running or exited child process.
71 /// This structure is used to represent and manage child processes. A child
72 /// process is created via the [`Command`] struct, which configures the
73 /// spawning process and can itself be constructed using a builder-style
76 /// There is no implementation of [`Drop`] for child processes,
77 /// so if you do not ensure the `Child` has exited then it will continue to
78 /// run, even after the `Child` handle to the child process has gone out of
81 /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
82 /// the parent process wait until the child has actually exited before
88 /// use std::process::Command;
90 /// let mut child = Command::new("/bin/cat")
93 /// .expect("failed to execute child");
95 /// let ecode = child.wait()
96 /// .expect("failed to wait on child");
98 /// assert!(ecode.success());
101 /// [`Command`]: struct.Command.html
102 /// [`Drop`]: ../../core/ops/trait.Drop.html
103 /// [`wait`]: #method.wait
104 #[stable(feature = "process", since = "1.0.0")]
106 handle: imp::Process,
108 /// The handle for writing to the child's stdin, if it has been captured
109 #[stable(feature = "process", since = "1.0.0")]
110 pub stdin: Option<ChildStdin>,
112 /// The handle for reading from the child's stdout, if it has been captured
113 #[stable(feature = "process", since = "1.0.0")]
114 pub stdout: Option<ChildStdout>,
116 /// The handle for reading from the child's stderr, if it has been captured
117 #[stable(feature = "process", since = "1.0.0")]
118 pub stderr: Option<ChildStderr>,
121 impl AsInner<imp::Process> for Child {
122 fn as_inner(&self) -> &imp::Process { &self.handle }
125 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
126 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
129 stdin: io.stdin.map(ChildStdin::from_inner),
130 stdout: io.stdout.map(ChildStdout::from_inner),
131 stderr: io.stderr.map(ChildStderr::from_inner),
136 impl IntoInner<imp::Process> for Child {
137 fn into_inner(self) -> imp::Process { self.handle }
140 #[stable(feature = "std_debug", since = "1.16.0")]
141 impl fmt::Debug for Child {
142 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
143 f.debug_struct("Child")
144 .field("stdin", &self.stdin)
145 .field("stdout", &self.stdout)
146 .field("stderr", &self.stderr)
151 /// A handle to a child process's stdin. This struct is used in the [`stdin`]
152 /// field on [`Child`].
154 /// [`Child`]: struct.Child.html
155 /// [`stdin`]: struct.Child.html#structfield.stdin
156 #[stable(feature = "process", since = "1.0.0")]
157 pub struct ChildStdin {
161 #[stable(feature = "process", since = "1.0.0")]
162 impl Write for ChildStdin {
163 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
164 self.inner.write(buf)
167 fn flush(&mut self) -> io::Result<()> {
172 impl AsInner<AnonPipe> for ChildStdin {
173 fn as_inner(&self) -> &AnonPipe { &self.inner }
176 impl IntoInner<AnonPipe> for ChildStdin {
177 fn into_inner(self) -> AnonPipe { self.inner }
180 impl FromInner<AnonPipe> for ChildStdin {
181 fn from_inner(pipe: AnonPipe) -> ChildStdin {
182 ChildStdin { inner: pipe }
186 #[stable(feature = "std_debug", since = "1.16.0")]
187 impl fmt::Debug for ChildStdin {
188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
189 f.pad("ChildStdin { .. }")
193 /// A handle to a child process's stdout. This struct is used in the [`stdout`]
194 /// field on [`Child`].
196 /// [`Child`]: struct.Child.html
197 /// [`stdout`]: struct.Child.html#structfield.stdout
198 #[stable(feature = "process", since = "1.0.0")]
199 pub struct ChildStdout {
203 #[stable(feature = "process", since = "1.0.0")]
204 impl Read for ChildStdout {
205 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
208 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
209 self.inner.read_to_end(buf)
213 impl AsInner<AnonPipe> for ChildStdout {
214 fn as_inner(&self) -> &AnonPipe { &self.inner }
217 impl IntoInner<AnonPipe> for ChildStdout {
218 fn into_inner(self) -> AnonPipe { self.inner }
221 impl FromInner<AnonPipe> for ChildStdout {
222 fn from_inner(pipe: AnonPipe) -> ChildStdout {
223 ChildStdout { inner: pipe }
227 #[stable(feature = "std_debug", since = "1.16.0")]
228 impl fmt::Debug for ChildStdout {
229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
230 f.pad("ChildStdout { .. }")
234 /// A handle to a child process's stderr.
236 /// This struct is used in the [`stderr`] field on [`Child`].
238 /// [`Child`]: struct.Child.html
239 /// [`stderr`]: struct.Child.html#structfield.stderr
240 #[stable(feature = "process", since = "1.0.0")]
241 pub struct ChildStderr {
245 #[stable(feature = "process", since = "1.0.0")]
246 impl Read for ChildStderr {
247 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
250 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
251 self.inner.read_to_end(buf)
255 impl AsInner<AnonPipe> for ChildStderr {
256 fn as_inner(&self) -> &AnonPipe { &self.inner }
259 impl IntoInner<AnonPipe> for ChildStderr {
260 fn into_inner(self) -> AnonPipe { self.inner }
263 impl FromInner<AnonPipe> for ChildStderr {
264 fn from_inner(pipe: AnonPipe) -> ChildStderr {
265 ChildStderr { inner: pipe }
269 #[stable(feature = "std_debug", since = "1.16.0")]
270 impl fmt::Debug for ChildStderr {
271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
272 f.pad("ChildStderr { .. }")
276 /// A process builder, providing fine-grained control
277 /// over how a new process should be spawned.
279 /// A default configuration can be
280 /// generated using `Command::new(program)`, where `program` gives a path to the
281 /// program to be executed. Additional builder methods allow the configuration
282 /// to be changed (for example, by adding arguments) prior to spawning:
285 /// use std::process::Command;
287 /// let output = if cfg!(target_os = "windows") {
288 /// Command::new("cmd")
289 /// .args(&["/C", "echo hello"])
291 /// .expect("failed to execute process")
293 /// Command::new("sh")
295 /// .arg("echo hello")
297 /// .expect("failed to execute process")
300 /// let hello = output.stdout;
302 #[stable(feature = "process", since = "1.0.0")]
308 /// Constructs a new `Command` for launching the program at
309 /// path `program`, with the following default configuration:
311 /// * No arguments to the program
312 /// * Inherit the current process's environment
313 /// * Inherit the current process's working directory
314 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
316 /// Builder methods are provided to change these defaults and
317 /// otherwise configure the process.
319 /// If `program` is not an absolute path, the `PATH` will be searched in
320 /// an OS-defined way.
322 /// The search path to be used may be controlled by setting the
323 /// `PATH` environment variable on the Command,
324 /// but this has some implementation limitations on Windows
325 /// (see https://github.com/rust-lang/rust/issues/37519).
332 /// use std::process::Command;
334 /// Command::new("sh")
336 /// .expect("sh command failed to start");
338 #[stable(feature = "process", since = "1.0.0")]
339 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
340 Command { inner: imp::Command::new(program.as_ref()) }
343 /// Add an argument to pass to the program.
345 /// Only one argument can be passed per use. So instead of:
348 /// .arg("-C /path/to/repo")
355 /// .arg("/path/to/repo")
358 /// To pass multiple arguments see [`args`].
360 /// [`args`]: #method.args
367 /// use std::process::Command;
369 /// Command::new("ls")
373 /// .expect("ls command failed to start");
375 #[stable(feature = "process", since = "1.0.0")]
376 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
377 self.inner.arg(arg.as_ref());
381 /// Add multiple arguments to pass to the program.
383 /// To pass a single argument see [`arg`].
385 /// [`arg`]: #method.arg
392 /// use std::process::Command;
394 /// Command::new("ls")
395 /// .args(&["-l", "-a"])
397 /// .expect("ls command failed to start");
399 #[stable(feature = "process", since = "1.0.0")]
400 pub fn args<I, S>(&mut self, args: I) -> &mut Command
401 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
404 self.arg(arg.as_ref());
409 /// Inserts or updates an environment variable mapping.
411 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
412 /// and case-sensitive on all other platforms.
419 /// use std::process::Command;
421 /// Command::new("ls")
422 /// .env("PATH", "/bin")
424 /// .expect("ls command failed to start");
426 #[stable(feature = "process", since = "1.0.0")]
427 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
428 where K: AsRef<OsStr>, V: AsRef<OsStr>
430 self.inner.env(key.as_ref(), val.as_ref());
434 /// Add or update multiple environment variable mappings.
441 /// #![feature(command_envs)]
443 /// use std::process::{Command, Stdio};
445 /// use std::collections::HashMap;
447 /// let filtered_env : HashMap<String, String> =
448 /// env::vars().filter(|&(ref k, _)|
449 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
452 /// Command::new("printenv")
453 /// .stdin(Stdio::null())
454 /// .stdout(Stdio::inherit())
456 /// .envs(&filtered_env)
458 /// .expect("printenv failed to start");
460 #[unstable(feature = "command_envs", issue = "38526")]
461 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
462 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
464 for (ref key, ref val) in vars {
465 self.inner.env(key.as_ref(), val.as_ref());
470 /// Removes an environment variable mapping.
477 /// use std::process::Command;
479 /// Command::new("ls")
480 /// .env_remove("PATH")
482 /// .expect("ls command failed to start");
484 #[stable(feature = "process", since = "1.0.0")]
485 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
486 self.inner.env_remove(key.as_ref());
490 /// Clears the entire environment map for the child process.
497 /// use std::process::Command;
499 /// Command::new("ls")
502 /// .expect("ls command failed to start");
504 #[stable(feature = "process", since = "1.0.0")]
505 pub fn env_clear(&mut self) -> &mut Command {
506 self.inner.env_clear();
510 /// Sets the working directory for the child process.
517 /// use std::process::Command;
519 /// Command::new("ls")
520 /// .current_dir("/bin")
522 /// .expect("ls command failed to start");
524 #[stable(feature = "process", since = "1.0.0")]
525 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
526 self.inner.cwd(dir.as_ref().as_ref());
530 /// Configuration for the child process's stdin handle (file descriptor 0).
537 /// use std::process::{Command, Stdio};
539 /// Command::new("ls")
540 /// .stdin(Stdio::null())
542 /// .expect("ls command failed to start");
544 #[stable(feature = "process", since = "1.0.0")]
545 pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
546 self.inner.stdin(cfg.0);
550 /// Configuration for the child process's stdout handle (file descriptor 1).
557 /// use std::process::{Command, Stdio};
559 /// Command::new("ls")
560 /// .stdout(Stdio::null())
562 /// .expect("ls command failed to start");
564 #[stable(feature = "process", since = "1.0.0")]
565 pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
566 self.inner.stdout(cfg.0);
570 /// Configuration for the child process's stderr handle (file descriptor 2).
577 /// use std::process::{Command, Stdio};
579 /// Command::new("ls")
580 /// .stderr(Stdio::null())
582 /// .expect("ls command failed to start");
584 #[stable(feature = "process", since = "1.0.0")]
585 pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
586 self.inner.stderr(cfg.0);
590 /// Executes the command as a child process, returning a handle to it.
592 /// By default, stdin, stdout and stderr are inherited from the parent.
599 /// use std::process::Command;
601 /// Command::new("ls")
603 /// .expect("ls command failed to start");
605 #[stable(feature = "process", since = "1.0.0")]
606 pub fn spawn(&mut self) -> io::Result<Child> {
607 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
610 /// Executes the command as a child process, waiting for it to finish and
611 /// collecting all of its output.
613 /// By default, stdin, stdout and stderr are captured (and used to
614 /// provide the resulting output).
619 /// use std::process::Command;
620 /// let output = Command::new("/bin/cat")
623 /// .expect("failed to execute process");
625 /// println!("status: {}", output.status);
626 /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
627 /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
629 /// assert!(output.status.success());
631 #[stable(feature = "process", since = "1.0.0")]
632 pub fn output(&mut self) -> io::Result<Output> {
633 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
634 .and_then(|p| p.wait_with_output())
637 /// Executes a command as a child process, waiting for it to finish and
638 /// collecting its exit status.
640 /// By default, stdin, stdout and stderr are inherited from the parent.
645 /// use std::process::Command;
647 /// let status = Command::new("/bin/cat")
650 /// .expect("failed to execute process");
652 /// println!("process exited with: {}", status);
654 /// assert!(status.success());
656 #[stable(feature = "process", since = "1.0.0")]
657 pub fn status(&mut self) -> io::Result<ExitStatus> {
658 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
659 .and_then(|mut p| p.wait())
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl fmt::Debug for Command {
665 /// Format the program and arguments of a Command for display. Any
666 /// non-utf8 data is lossily converted using the utf8 replacement
668 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
673 impl AsInner<imp::Command> for Command {
674 fn as_inner(&self) -> &imp::Command { &self.inner }
677 impl AsInnerMut<imp::Command> for Command {
678 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
681 /// The output of a finished process.
682 #[derive(PartialEq, Eq, Clone)]
683 #[stable(feature = "process", since = "1.0.0")]
685 /// The status (exit code) of the process.
686 #[stable(feature = "process", since = "1.0.0")]
687 pub status: ExitStatus,
688 /// The data that the process wrote to stdout.
689 #[stable(feature = "process", since = "1.0.0")]
691 /// The data that the process wrote to stderr.
692 #[stable(feature = "process", since = "1.0.0")]
696 // If either stderr or stdout are valid utf8 strings it prints the valid
697 // strings, otherwise it prints the byte sequence instead
698 #[stable(feature = "process_output_debug", since = "1.7.0")]
699 impl fmt::Debug for Output {
700 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
702 let stdout_utf8 = str::from_utf8(&self.stdout);
703 let stdout_debug: &fmt::Debug = match stdout_utf8 {
705 Err(_) => &self.stdout
708 let stderr_utf8 = str::from_utf8(&self.stderr);
709 let stderr_debug: &fmt::Debug = match stderr_utf8 {
711 Err(_) => &self.stderr
714 fmt.debug_struct("Output")
715 .field("status", &self.status)
716 .field("stdout", stdout_debug)
717 .field("stderr", stderr_debug)
722 /// Describes what to do with a standard I/O stream for a child process.
723 #[stable(feature = "process", since = "1.0.0")]
724 pub struct Stdio(imp::Stdio);
727 /// A new pipe should be arranged to connect the parent and child processes.
728 #[stable(feature = "process", since = "1.0.0")]
729 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
731 /// The child inherits from the corresponding parent descriptor.
732 #[stable(feature = "process", since = "1.0.0")]
733 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
735 /// This stream will be ignored. This is the equivalent of attaching the
736 /// stream to `/dev/null`
737 #[stable(feature = "process", since = "1.0.0")]
738 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
741 impl FromInner<imp::Stdio> for Stdio {
742 fn from_inner(inner: imp::Stdio) -> Stdio {
747 #[stable(feature = "std_debug", since = "1.16.0")]
748 impl fmt::Debug for Stdio {
749 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
750 f.pad("Stdio { .. }")
754 /// Describes the result of a process after it has terminated.
755 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
756 #[stable(feature = "process", since = "1.0.0")]
757 pub struct ExitStatus(imp::ExitStatus);
760 /// Was termination successful? Signal termination not considered a success,
761 /// and success is defined as a zero exit status.
766 /// use std::process::Command;
768 /// let status = Command::new("mkdir")
771 /// .expect("failed to execute mkdir");
773 /// if status.success() {
774 /// println!("'projects/' directory created");
776 /// println!("failed to create 'projects/' directory");
779 #[stable(feature = "process", since = "1.0.0")]
780 pub fn success(&self) -> bool {
784 /// Returns the exit code of the process, if any.
786 /// On Unix, this will return `None` if the process was terminated
787 /// by a signal; `std::os::unix` provides an extension trait for
788 /// extracting the signal and other details from the `ExitStatus`.
789 #[stable(feature = "process", since = "1.0.0")]
790 pub fn code(&self) -> Option<i32> {
795 impl AsInner<imp::ExitStatus> for ExitStatus {
796 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
799 impl FromInner<imp::ExitStatus> for ExitStatus {
800 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
805 #[stable(feature = "process", since = "1.0.0")]
806 impl fmt::Display for ExitStatus {
807 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813 /// Forces the child to exit. This is equivalent to sending a
814 /// SIGKILL on unix platforms.
821 /// use std::process::Command;
823 /// let mut command = Command::new("yes");
824 /// if let Ok(mut child) = command.spawn() {
825 /// child.kill().expect("command wasn't running");
827 /// println!("yes command didn't start");
830 #[stable(feature = "process", since = "1.0.0")]
831 pub fn kill(&mut self) -> io::Result<()> {
835 /// Returns the OS-assigned process identifier associated with this child.
842 /// use std::process::Command;
844 /// let mut command = Command::new("ls");
845 /// if let Ok(child) = command.spawn() {
846 /// println!("Child's id is {}", child.id());
848 /// println!("ls command didn't start");
851 #[stable(feature = "process_id", since = "1.3.0")]
852 pub fn id(&self) -> u32 {
856 /// Waits for the child to exit completely, returning the status that it
857 /// exited with. This function will continue to have the same return value
858 /// after it has been called at least once.
860 /// The stdin handle to the child process, if any, will be closed
861 /// before waiting. This helps avoid deadlock: it ensures that the
862 /// child does not block waiting for input from the parent, while
863 /// the parent waits for the child to exit.
870 /// use std::process::Command;
872 /// let mut command = Command::new("ls");
873 /// if let Ok(mut child) = command.spawn() {
874 /// child.wait().expect("command wasn't running");
875 /// println!("Child has finished its execution!");
877 /// println!("ls command didn't start");
880 #[stable(feature = "process", since = "1.0.0")]
881 pub fn wait(&mut self) -> io::Result<ExitStatus> {
882 drop(self.stdin.take());
883 self.handle.wait().map(ExitStatus)
886 /// Attempts to collect the exit status of the child if it has already
889 /// This function will not block the calling thread and will only advisorily
890 /// check to see if the child process has exited or not. If the child has
891 /// exited then on Unix the process id is reaped. This function is
892 /// guaranteed to repeatedly return a successful exit status so long as the
893 /// child has already exited.
895 /// If the child has exited, then `Ok(Some(status))` is returned. If the
896 /// exit status is not available at this time then `Ok(None)` is returned.
897 /// If an error occurs, then that error is returned.
899 /// Note that unlike `wait`, this function will not attempt to drop stdin.
906 /// #![feature(process_try_wait)]
908 /// use std::process::Command;
910 /// let mut child = Command::new("ls").spawn().unwrap();
912 /// match child.try_wait() {
913 /// Ok(Some(status)) => println!("exited with: {}", status),
915 /// println!("status not ready yet, let's really wait");
916 /// let res = child.wait();
917 /// println!("result: {:?}", res);
919 /// Err(e) => println!("error attempting to wait: {}", e),
922 #[unstable(feature = "process_try_wait", issue = "38903")]
923 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
924 Ok(self.handle.try_wait()?.map(ExitStatus))
927 /// Simultaneously waits for the child to exit and collect all remaining
928 /// output on the stdout/stderr handles, returning an `Output`
931 /// The stdin handle to the child process, if any, will be closed
932 /// before waiting. This helps avoid deadlock: it ensures that the
933 /// child does not block waiting for input from the parent, while
934 /// the parent waits for the child to exit.
936 /// By default, stdin, stdout and stderr are inherited from the parent.
937 /// In order to capture the output into this `Result<Output>` it is
938 /// necessary to create new pipes between parent and child. Use
939 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
944 /// use std::process::{Command, Stdio};
946 /// let child = Command::new("/bin/cat")
948 /// .stdout(Stdio::piped())
950 /// .expect("failed to execute child");
952 /// let output = child
953 /// .wait_with_output()
954 /// .expect("failed to wait on child");
956 /// assert!(output.status.success());
959 #[stable(feature = "process", since = "1.0.0")]
960 pub fn wait_with_output(mut self) -> io::Result<Output> {
961 drop(self.stdin.take());
963 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
964 match (self.stdout.take(), self.stderr.take()) {
966 (Some(mut out), None) => {
967 let res = out.read_to_end(&mut stdout);
970 (None, Some(mut err)) => {
971 let res = err.read_to_end(&mut stderr);
974 (Some(out), Some(err)) => {
975 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
980 let status = self.wait()?;
989 /// Terminates the current process with the specified exit code.
991 /// This function will never return and will immediately terminate the current
992 /// process. The exit code is passed through to the underlying OS and will be
993 /// available for consumption by another process.
995 /// Note that because this function never returns, and that it terminates the
996 /// process, no destructors on the current stack or any other thread's stack
997 /// will be run. If a clean shutdown is needed it is recommended to only call
998 /// this function at a known point where there are no more destructors left
1001 /// ## Platform-specific behavior
1003 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
1004 /// will be visible to a parent process inspecting the exit code. On most
1005 /// Unix-like platforms, only the eight least-significant bits are considered.
1009 /// Due to this function’s behavior regarding destructors, a conventional way
1010 /// to use the function is to extract the actual computation to another
1011 /// function and compute the exit code from its return value:
1014 /// use std::io::{self, Write};
1016 /// fn run_app() -> Result<(), ()> {
1017 /// // Application logic here
1022 /// ::std::process::exit(match run_app() {
1025 /// writeln!(io::stderr(), "error: {:?}", err).unwrap();
1032 /// Due to [platform-specific behavior], the exit code for this example will be
1033 /// `0` on Linux, but `256` on Windows:
1036 /// use std::process;
1038 /// process::exit(0x0f00);
1041 /// [platform-specific behavior]: #platform-specific-behavior
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn exit(code: i32) -> ! {
1044 ::sys_common::cleanup();
1045 ::sys::os::exit(code)
1048 /// Terminates the process in an abnormal fashion.
1050 /// The function will never return and will immediately terminate the current
1051 /// process in a platform specific "abnormal" manner.
1053 /// Note that because this function never returns, and that it terminates the
1054 /// process, no destructors on the current stack or any other thread's stack
1055 /// will be run. If a clean shutdown is needed it is recommended to only call
1056 /// this function at a known point where there are no more destructors left
1062 /// use std::process;
1065 /// println!("aborting");
1067 /// process::abort();
1069 /// // execution never gets here
1073 /// The [`abort`] function terminates the process, so the destructor will not
1074 /// get run on the example below:
1077 /// use std::process;
1081 /// impl Drop for HasDrop {
1082 /// fn drop(&mut self) {
1083 /// println!("This will never be printed!");
1088 /// let _x = HasDrop;
1089 /// process::abort();
1090 /// // the destructor implemented for HasDrop will never get run
1093 #[stable(feature = "process_abort", since = "1.17.0")]
1094 pub fn abort() -> ! {
1095 unsafe { ::sys::abort_internal() };
1098 #[cfg(all(test, not(target_os = "emscripten")))]
1104 use super::{Command, Output, Stdio};
1106 // FIXME(#10380) these tests should not all be ignored on android.
1109 #[cfg_attr(target_os = "android", ignore)]
1111 let p = if cfg!(target_os = "windows") {
1112 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1114 Command::new("true").spawn()
1117 let mut p = p.unwrap();
1118 assert!(p.wait().unwrap().success());
1122 #[cfg_attr(target_os = "android", ignore)]
1123 fn smoke_failure() {
1124 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1131 #[cfg_attr(target_os = "android", ignore)]
1132 fn exit_reported_right() {
1133 let p = if cfg!(target_os = "windows") {
1134 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1136 Command::new("false").spawn()
1139 let mut p = p.unwrap();
1140 assert!(p.wait().unwrap().code() == Some(1));
1146 #[cfg_attr(target_os = "android", ignore)]
1147 fn signal_reported_right() {
1148 use os::unix::process::ExitStatusExt;
1150 let mut p = Command::new("/bin/sh")
1151 .arg("-c").arg("read a")
1152 .stdin(Stdio::piped())
1155 match p.wait().unwrap().signal() {
1157 result => panic!("not terminated by signal 9 (instead, {:?})",
1162 pub fn run_output(mut cmd: Command) -> String {
1163 let p = cmd.spawn();
1165 let mut p = p.unwrap();
1166 assert!(p.stdout.is_some());
1167 let mut ret = String::new();
1168 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1169 assert!(p.wait().unwrap().success());
1174 #[cfg_attr(target_os = "android", ignore)]
1176 if cfg!(target_os = "windows") {
1177 let mut cmd = Command::new("cmd");
1178 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1179 assert_eq!(run_output(cmd), "foobar\r\n");
1181 let mut cmd = Command::new("echo");
1182 cmd.arg("foobar").stdout(Stdio::piped());
1183 assert_eq!(run_output(cmd), "foobar\n");
1188 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1189 fn set_current_dir_works() {
1190 let mut cmd = Command::new("/bin/sh");
1191 cmd.arg("-c").arg("pwd")
1193 .stdout(Stdio::piped());
1194 assert_eq!(run_output(cmd), "/\n");
1198 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1200 let mut p = Command::new("/bin/sh")
1201 .arg("-c").arg("read line; echo $line")
1202 .stdin(Stdio::piped())
1203 .stdout(Stdio::piped())
1205 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1206 drop(p.stdin.take());
1207 let mut out = String::new();
1208 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1209 assert!(p.wait().unwrap().success());
1210 assert_eq!(out, "foobar\n");
1215 #[cfg_attr(target_os = "android", ignore)]
1218 use os::unix::prelude::*;
1220 let mut p = Command::new("/bin/sh")
1221 .arg("-c").arg("true")
1222 .uid(unsafe { libc::getuid() })
1223 .gid(unsafe { libc::getgid() })
1225 assert!(p.wait().unwrap().success());
1229 #[cfg_attr(target_os = "android", ignore)]
1231 fn uid_to_root_fails() {
1232 use os::unix::prelude::*;
1235 // if we're already root, this isn't a valid test. Most of the bots run
1236 // as non-root though (android is an exception).
1237 if unsafe { libc::getuid() == 0 } { return }
1238 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1242 #[cfg_attr(target_os = "android", ignore)]
1243 fn test_process_status() {
1244 let mut status = if cfg!(target_os = "windows") {
1245 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1247 Command::new("false").status().unwrap()
1249 assert!(status.code() == Some(1));
1251 status = if cfg!(target_os = "windows") {
1252 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1254 Command::new("true").status().unwrap()
1256 assert!(status.success());
1260 fn test_process_output_fail_to_start() {
1261 match Command::new("/no-binary-by-this-name-should-exist").output() {
1262 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1268 #[cfg_attr(target_os = "android", ignore)]
1269 fn test_process_output_output() {
1270 let Output {status, stdout, stderr}
1271 = if cfg!(target_os = "windows") {
1272 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1274 Command::new("echo").arg("hello").output().unwrap()
1276 let output_str = str::from_utf8(&stdout).unwrap();
1278 assert!(status.success());
1279 assert_eq!(output_str.trim().to_string(), "hello");
1280 assert_eq!(stderr, Vec::new());
1284 #[cfg_attr(target_os = "android", ignore)]
1285 fn test_process_output_error() {
1286 let Output {status, stdout, stderr}
1287 = if cfg!(target_os = "windows") {
1288 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1290 Command::new("mkdir").arg(".").output().unwrap()
1293 assert!(status.code() == Some(1));
1294 assert_eq!(stdout, Vec::new());
1295 assert!(!stderr.is_empty());
1299 #[cfg_attr(target_os = "android", ignore)]
1300 fn test_finish_once() {
1301 let mut prog = if cfg!(target_os = "windows") {
1302 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1304 Command::new("false").spawn().unwrap()
1306 assert!(prog.wait().unwrap().code() == Some(1));
1310 #[cfg_attr(target_os = "android", ignore)]
1311 fn test_finish_twice() {
1312 let mut prog = if cfg!(target_os = "windows") {
1313 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1315 Command::new("false").spawn().unwrap()
1317 assert!(prog.wait().unwrap().code() == Some(1));
1318 assert!(prog.wait().unwrap().code() == Some(1));
1322 #[cfg_attr(target_os = "android", ignore)]
1323 fn test_wait_with_output_once() {
1324 let prog = if cfg!(target_os = "windows") {
1325 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1327 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1330 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1331 let output_str = str::from_utf8(&stdout).unwrap();
1333 assert!(status.success());
1334 assert_eq!(output_str.trim().to_string(), "hello");
1335 assert_eq!(stderr, Vec::new());
1338 #[cfg(all(unix, not(target_os="android")))]
1339 pub fn env_cmd() -> Command {
1342 #[cfg(target_os="android")]
1343 pub fn env_cmd() -> Command {
1344 let mut cmd = Command::new("/system/bin/sh");
1345 cmd.arg("-c").arg("set");
1350 pub fn env_cmd() -> Command {
1351 let mut cmd = Command::new("cmd");
1352 cmd.arg("/c").arg("set");
1357 fn test_inherit_env() {
1360 let result = env_cmd().output().unwrap();
1361 let output = String::from_utf8(result.stdout).unwrap();
1363 for (ref k, ref v) in env::vars() {
1364 // don't check android RANDOM variables
1365 if cfg!(target_os = "android") && *k == "RANDOM" {
1369 // Windows has hidden environment variables whose names start with
1370 // equals signs (`=`). Those do not show up in the output of the
1372 assert!((cfg!(windows) && k.starts_with("=")) ||
1373 k.starts_with("DYLD") ||
1374 output.contains(&format!("{}={}", *k, *v)) ||
1375 output.contains(&format!("{}='{}'", *k, *v)),
1376 "output doesn't contain `{}={}`\n{}",
1382 fn test_override_env() {
1385 // In some build environments (such as chrooted Nix builds), `env` can
1386 // only be found in the explicitly-provided PATH env variable, not in
1387 // default places such as /bin or /usr/bin. So we need to pass through
1388 // PATH to our sub-process.
1389 let mut cmd = env_cmd();
1390 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1391 if let Some(p) = env::var_os("PATH") {
1392 cmd.env("PATH", &p);
1394 let result = cmd.output().unwrap();
1395 let output = String::from_utf8_lossy(&result.stdout).to_string();
1397 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1398 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1402 fn test_add_to_env() {
1403 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1404 let output = String::from_utf8_lossy(&result.stdout).to_string();
1406 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1407 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1410 // Regression tests for #30858.
1412 fn test_interior_nul_in_progname_is_error() {
1413 match Command::new("has-some-\0\0s-inside").spawn() {
1414 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1420 fn test_interior_nul_in_arg_is_error() {
1421 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1422 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1428 fn test_interior_nul_in_args_is_error() {
1429 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1430 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1436 fn test_interior_nul_in_current_dir_is_error() {
1437 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1438 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1443 // Regression tests for #30862.
1445 fn test_interior_nul_in_env_key_is_error() {
1446 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1447 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1453 fn test_interior_nul_in_env_value_is_error() {
1454 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1455 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1460 /// Test that process creation flags work by debugging a process.
1461 /// Other creation flags make it hard or impossible to detect
1462 /// behavioral changes in the process.
1465 fn test_creation_flags() {
1466 use os::windows::process::CommandExt;
1467 use sys::c::{BOOL, DWORD, INFINITE};
1469 struct DEBUG_EVENT {
1470 pub event_code: DWORD,
1471 pub process_id: DWORD,
1472 pub thread_id: DWORD,
1473 // This is a union in the real struct, but we don't
1474 // need this data for the purposes of this test.
1475 pub _junk: [u8; 164],
1479 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1480 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1481 dwContinueStatus: DWORD) -> BOOL;
1484 const DEBUG_PROCESS: DWORD = 1;
1485 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1486 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1488 let mut child = Command::new("cmd")
1489 .creation_flags(DEBUG_PROCESS)
1490 .stdin(Stdio::piped()).spawn().unwrap();
1491 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1493 let mut event = DEBUG_EVENT {
1500 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1501 panic!("WaitForDebugEvent failed!");
1505 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1509 if unsafe { ContinueDebugEvent(event.process_id,
1511 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1512 panic!("ContinueDebugEvent failed!");
1515 assert!(events > 0);