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 #![stable(feature = "process", since = "1.0.0")]
40 use sys::pipe::{read2, AnonPipe};
41 use sys::process as imp;
42 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
44 /// Representation of a running or exited child process.
46 /// This structure is used to represent and manage child processes. A child
47 /// process is created via the [`Command`] struct, which configures the
48 /// spawning process and can itself be constructed using a builder-style
54 /// use std::process::Command;
56 /// let mut child = Command::new("/bin/cat")
59 /// .expect("failed to execute child");
61 /// let ecode = child.wait()
62 /// .expect("failed to wait on child");
64 /// assert!(ecode.success());
69 /// Take note that there is no implementation of [`Drop`] for child processes,
70 /// so if you do not ensure the `Child` has exited then it will continue to
71 /// run, even after the `Child` handle to the child process has gone out of
74 /// Calling [`wait`][`wait`] (or other functions that wrap around it) will make
75 /// the parent process wait until the child has actually exited before
78 /// [`Command`]: struct.Command.html
79 /// [`Drop`]: ../../core/ops/trait.Drop.html
80 /// [`wait`]: #method.wait
81 #[stable(feature = "process", since = "1.0.0")]
85 /// The handle for writing to the child's stdin, if it has been captured
86 #[stable(feature = "process", since = "1.0.0")]
87 pub stdin: Option<ChildStdin>,
89 /// The handle for reading from the child's stdout, if it has been captured
90 #[stable(feature = "process", since = "1.0.0")]
91 pub stdout: Option<ChildStdout>,
93 /// The handle for reading from the child's stderr, if it has been captured
94 #[stable(feature = "process", since = "1.0.0")]
95 pub stderr: Option<ChildStderr>,
98 impl AsInner<imp::Process> for Child {
99 fn as_inner(&self) -> &imp::Process { &self.handle }
102 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
103 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
106 stdin: io.stdin.map(ChildStdin::from_inner),
107 stdout: io.stdout.map(ChildStdout::from_inner),
108 stderr: io.stderr.map(ChildStderr::from_inner),
113 impl IntoInner<imp::Process> for Child {
114 fn into_inner(self) -> imp::Process { self.handle }
117 #[stable(feature = "std_debug", since = "1.16.0")]
118 impl fmt::Debug for Child {
119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120 f.debug_struct("Child")
121 .field("stdin", &self.stdin)
122 .field("stdout", &self.stdout)
123 .field("stderr", &self.stderr)
128 /// A handle to a child process's stdin. This struct is used in the [`stdin`]
129 /// field on [`Child`].
131 /// [`Child`]: struct.Child.html
132 /// [`stdin`]: struct.Child.html#structfield.stdin
133 #[stable(feature = "process", since = "1.0.0")]
134 pub struct ChildStdin {
138 #[stable(feature = "process", since = "1.0.0")]
139 impl Write for ChildStdin {
140 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
141 self.inner.write(buf)
144 fn flush(&mut self) -> io::Result<()> {
149 impl AsInner<AnonPipe> for ChildStdin {
150 fn as_inner(&self) -> &AnonPipe { &self.inner }
153 impl IntoInner<AnonPipe> for ChildStdin {
154 fn into_inner(self) -> AnonPipe { self.inner }
157 impl FromInner<AnonPipe> for ChildStdin {
158 fn from_inner(pipe: AnonPipe) -> ChildStdin {
159 ChildStdin { inner: pipe }
163 #[stable(feature = "std_debug", since = "1.16.0")]
164 impl fmt::Debug for ChildStdin {
165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166 f.pad("ChildStdin { .. }")
170 /// A handle to a child process's stdout. This struct is used in the [`stdout`]
171 /// field on [`Child`].
173 /// [`Child`]: struct.Child.html
174 /// [`stdout`]: struct.Child.html#structfield.stdout
175 #[stable(feature = "process", since = "1.0.0")]
176 pub struct ChildStdout {
180 #[stable(feature = "process", since = "1.0.0")]
181 impl Read for ChildStdout {
182 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
185 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
186 self.inner.read_to_end(buf)
190 impl AsInner<AnonPipe> for ChildStdout {
191 fn as_inner(&self) -> &AnonPipe { &self.inner }
194 impl IntoInner<AnonPipe> for ChildStdout {
195 fn into_inner(self) -> AnonPipe { self.inner }
198 impl FromInner<AnonPipe> for ChildStdout {
199 fn from_inner(pipe: AnonPipe) -> ChildStdout {
200 ChildStdout { inner: pipe }
204 #[stable(feature = "std_debug", since = "1.16.0")]
205 impl fmt::Debug for ChildStdout {
206 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207 f.pad("ChildStdout { .. }")
211 /// A handle to a child process's stderr. This struct is used in the [`stderr`]
212 /// field on [`Child`].
214 /// [`Child`]: struct.Child.html
215 /// [`stderr`]: struct.Child.html#structfield.stderr
216 #[stable(feature = "process", since = "1.0.0")]
217 pub struct ChildStderr {
221 #[stable(feature = "process", since = "1.0.0")]
222 impl Read for ChildStderr {
223 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
226 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
227 self.inner.read_to_end(buf)
231 impl AsInner<AnonPipe> for ChildStderr {
232 fn as_inner(&self) -> &AnonPipe { &self.inner }
235 impl IntoInner<AnonPipe> for ChildStderr {
236 fn into_inner(self) -> AnonPipe { self.inner }
239 impl FromInner<AnonPipe> for ChildStderr {
240 fn from_inner(pipe: AnonPipe) -> ChildStderr {
241 ChildStderr { inner: pipe }
245 #[stable(feature = "std_debug", since = "1.16.0")]
246 impl fmt::Debug for ChildStderr {
247 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248 f.pad("ChildStderr { .. }")
252 /// A process builder, providing fine-grained control
253 /// over how a new process should be spawned.
255 /// A default configuration can be
256 /// generated using `Command::new(program)`, where `program` gives a path to the
257 /// program to be executed. Additional builder methods allow the configuration
258 /// to be changed (for example, by adding arguments) prior to spawning:
261 /// use std::process::Command;
263 /// let output = if cfg!(target_os = "windows") {
264 /// Command::new("cmd")
265 /// .args(&["/C", "echo hello"])
267 /// .expect("failed to execute process")
269 /// Command::new("sh")
271 /// .arg("echo hello")
273 /// .expect("failed to execute process")
276 /// let hello = output.stdout;
278 #[stable(feature = "process", since = "1.0.0")]
284 /// Constructs a new `Command` for launching the program at
285 /// path `program`, with the following default configuration:
287 /// * No arguments to the program
288 /// * Inherit the current process's environment
289 /// * Inherit the current process's working directory
290 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
292 /// Builder methods are provided to change these defaults and
293 /// otherwise configure the process.
295 /// If `program` is not an absolute path, the `PATH` will be searched in
296 /// an OS-defined way.
298 /// The search path to be used may be controlled by setting the
299 /// `PATH` environment variable on the Command,
300 /// but this has some implementation limitations on Windows
301 /// (see https://github.com/rust-lang/rust/issues/37519).
308 /// use std::process::Command;
310 /// Command::new("sh")
312 /// .expect("sh command failed to start");
314 #[stable(feature = "process", since = "1.0.0")]
315 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
316 Command { inner: imp::Command::new(program.as_ref()) }
319 /// Add an argument to pass to the program.
326 /// use std::process::Command;
328 /// Command::new("ls")
332 /// .expect("ls command failed to start");
334 #[stable(feature = "process", since = "1.0.0")]
335 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
336 self.inner.arg(arg.as_ref());
340 /// Add multiple arguments to pass to the program.
347 /// use std::process::Command;
349 /// Command::new("ls")
350 /// .args(&["-l", "-a"])
352 /// .expect("ls command failed to start");
354 #[stable(feature = "process", since = "1.0.0")]
355 pub fn args<I, S>(&mut self, args: I) -> &mut Command
356 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
359 self.arg(arg.as_ref());
364 /// Inserts or updates an environment variable mapping.
366 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
367 /// and case-sensitive on all other platforms.
374 /// use std::process::Command;
376 /// Command::new("ls")
377 /// .env("PATH", "/bin")
379 /// .expect("ls command failed to start");
381 #[stable(feature = "process", since = "1.0.0")]
382 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
383 where K: AsRef<OsStr>, V: AsRef<OsStr>
385 self.inner.env(key.as_ref(), val.as_ref());
389 /// Add or update multiple environment variable mappings.
395 /// use std::process::{Command, Stdio};
397 /// use std::collections::HashMap;
399 /// let filtered_env : HashMap<String, String> =
400 /// env::vars().filter(|&(ref k, _)|
401 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
404 /// Command::new("printenv")
405 /// .stdin(Stdio::null())
406 /// .stdout(Stdio::inherit())
408 /// .envs(&filtered_env)
410 /// .expect("printenv failed to start");
412 #[unstable(feature = "command_envs", issue = "38526")]
413 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
414 where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
416 for (ref key, ref val) in vars {
417 self.inner.env(key.as_ref(), val.as_ref());
422 /// Removes an environment variable mapping.
429 /// use std::process::Command;
431 /// Command::new("ls")
432 /// .env_remove("PATH")
434 /// .expect("ls command failed to start");
436 #[stable(feature = "process", since = "1.0.0")]
437 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
438 self.inner.env_remove(key.as_ref());
442 /// Clears the entire environment map for the child process.
449 /// use std::process::Command;
451 /// Command::new("ls")
454 /// .expect("ls command failed to start");
456 #[stable(feature = "process", since = "1.0.0")]
457 pub fn env_clear(&mut self) -> &mut Command {
458 self.inner.env_clear();
462 /// Sets the working directory for the child process.
469 /// use std::process::Command;
471 /// Command::new("ls")
472 /// .current_dir("/bin")
474 /// .expect("ls command failed to start");
476 #[stable(feature = "process", since = "1.0.0")]
477 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
478 self.inner.cwd(dir.as_ref().as_ref());
482 /// Configuration for the child process's stdin handle (file descriptor 0).
489 /// use std::process::{Command, Stdio};
491 /// Command::new("ls")
492 /// .stdin(Stdio::null())
494 /// .expect("ls command failed to start");
496 #[stable(feature = "process", since = "1.0.0")]
497 pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
498 self.inner.stdin(cfg.0);
502 /// Configuration for the child process's stdout handle (file descriptor 1).
509 /// use std::process::{Command, Stdio};
511 /// Command::new("ls")
512 /// .stdout(Stdio::null())
514 /// .expect("ls command failed to start");
516 #[stable(feature = "process", since = "1.0.0")]
517 pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
518 self.inner.stdout(cfg.0);
522 /// Configuration for the child process's stderr handle (file descriptor 2).
529 /// use std::process::{Command, Stdio};
531 /// Command::new("ls")
532 /// .stderr(Stdio::null())
534 /// .expect("ls command failed to start");
536 #[stable(feature = "process", since = "1.0.0")]
537 pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
538 self.inner.stderr(cfg.0);
542 /// Executes the command as a child process, returning a handle to it.
544 /// By default, stdin, stdout and stderr are inherited from the parent.
551 /// use std::process::Command;
553 /// Command::new("ls")
555 /// .expect("ls command failed to start");
557 #[stable(feature = "process", since = "1.0.0")]
558 pub fn spawn(&mut self) -> io::Result<Child> {
559 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
562 /// Executes the command as a child process, waiting for it to finish and
563 /// collecting all of its output.
565 /// By default, stdin, stdout and stderr are captured (and used to
566 /// provide the resulting output).
571 /// use std::process::Command;
572 /// let output = Command::new("/bin/cat")
575 /// .expect("failed to execute process");
577 /// println!("status: {}", output.status);
578 /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
579 /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
581 /// assert!(output.status.success());
583 #[stable(feature = "process", since = "1.0.0")]
584 pub fn output(&mut self) -> io::Result<Output> {
585 self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
586 .and_then(|p| p.wait_with_output())
589 /// Executes a command as a child process, waiting for it to finish and
590 /// collecting its exit status.
592 /// By default, stdin, stdout and stderr are inherited from the parent.
597 /// use std::process::Command;
599 /// let status = Command::new("/bin/cat")
602 /// .expect("failed to execute process");
604 /// println!("process exited with: {}", status);
606 /// assert!(status.success());
608 #[stable(feature = "process", since = "1.0.0")]
609 pub fn status(&mut self) -> io::Result<ExitStatus> {
610 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
611 .and_then(|mut p| p.wait())
615 #[stable(feature = "rust1", since = "1.0.0")]
616 impl fmt::Debug for Command {
617 /// Format the program and arguments of a Command for display. Any
618 /// non-utf8 data is lossily converted using the utf8 replacement
620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
625 impl AsInner<imp::Command> for Command {
626 fn as_inner(&self) -> &imp::Command { &self.inner }
629 impl AsInnerMut<imp::Command> for Command {
630 fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
633 /// The output of a finished process.
634 #[derive(PartialEq, Eq, Clone)]
635 #[stable(feature = "process", since = "1.0.0")]
637 /// The status (exit code) of the process.
638 #[stable(feature = "process", since = "1.0.0")]
639 pub status: ExitStatus,
640 /// The data that the process wrote to stdout.
641 #[stable(feature = "process", since = "1.0.0")]
643 /// The data that the process wrote to stderr.
644 #[stable(feature = "process", since = "1.0.0")]
648 // If either stderr or stdout are valid utf8 strings it prints the valid
649 // strings, otherwise it prints the byte sequence instead
650 #[stable(feature = "process_output_debug", since = "1.7.0")]
651 impl fmt::Debug for Output {
652 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
654 let stdout_utf8 = str::from_utf8(&self.stdout);
655 let stdout_debug: &fmt::Debug = match stdout_utf8 {
657 Err(_) => &self.stdout
660 let stderr_utf8 = str::from_utf8(&self.stderr);
661 let stderr_debug: &fmt::Debug = match stderr_utf8 {
663 Err(_) => &self.stderr
666 fmt.debug_struct("Output")
667 .field("status", &self.status)
668 .field("stdout", stdout_debug)
669 .field("stderr", stderr_debug)
674 /// Describes what to do with a standard I/O stream for a child process.
675 #[stable(feature = "process", since = "1.0.0")]
676 pub struct Stdio(imp::Stdio);
679 /// A new pipe should be arranged to connect the parent and child processes.
680 #[stable(feature = "process", since = "1.0.0")]
681 pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
683 /// The child inherits from the corresponding parent descriptor.
684 #[stable(feature = "process", since = "1.0.0")]
685 pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
687 /// This stream will be ignored. This is the equivalent of attaching the
688 /// stream to `/dev/null`
689 #[stable(feature = "process", since = "1.0.0")]
690 pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
693 impl FromInner<imp::Stdio> for Stdio {
694 fn from_inner(inner: imp::Stdio) -> Stdio {
699 #[stable(feature = "std_debug", since = "1.16.0")]
700 impl fmt::Debug for Stdio {
701 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
702 f.pad("Stdio { .. }")
706 /// Describes the result of a process after it has terminated.
707 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
708 #[stable(feature = "process", since = "1.0.0")]
709 pub struct ExitStatus(imp::ExitStatus);
712 /// Was termination successful? Signal termination not considered a success,
713 /// and success is defined as a zero exit status.
718 /// use std::process::Command;
720 /// let status = Command::new("mkdir")
723 /// .expect("failed to execute mkdir");
725 /// if status.success() {
726 /// println!("'projects/' directory created");
728 /// println!("failed to create 'projects/' directory");
731 #[stable(feature = "process", since = "1.0.0")]
732 pub fn success(&self) -> bool {
736 /// Returns the exit code of the process, if any.
738 /// On Unix, this will return `None` if the process was terminated
739 /// by a signal; `std::os::unix` provides an extension trait for
740 /// extracting the signal and other details from the `ExitStatus`.
741 #[stable(feature = "process", since = "1.0.0")]
742 pub fn code(&self) -> Option<i32> {
747 impl AsInner<imp::ExitStatus> for ExitStatus {
748 fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
751 impl FromInner<imp::ExitStatus> for ExitStatus {
752 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
757 #[stable(feature = "process", since = "1.0.0")]
758 impl fmt::Display for ExitStatus {
759 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
765 /// Forces the child to exit. This is equivalent to sending a
766 /// SIGKILL on unix platforms.
773 /// use std::process::Command;
775 /// let mut command = Command::new("yes");
776 /// if let Ok(mut child) = command.spawn() {
777 /// child.kill().expect("command wasn't running");
779 /// println!("yes command didn't start");
782 #[stable(feature = "process", since = "1.0.0")]
783 pub fn kill(&mut self) -> io::Result<()> {
787 /// Returns the OS-assigned process identifier associated with this child.
794 /// use std::process::Command;
796 /// let mut command = Command::new("ls");
797 /// if let Ok(child) = command.spawn() {
798 /// println!("Child's id is {}", child.id());
800 /// println!("ls command didn't start");
803 #[stable(feature = "process_id", since = "1.3.0")]
804 pub fn id(&self) -> u32 {
808 /// Waits for the child to exit completely, returning the status that it
809 /// exited with. This function will continue to have the same return value
810 /// after it has been called at least once.
812 /// The stdin handle to the child process, if any, will be closed
813 /// before waiting. This helps avoid deadlock: it ensures that the
814 /// child does not block waiting for input from the parent, while
815 /// the parent waits for the child to exit.
822 /// use std::process::Command;
824 /// let mut command = Command::new("ls");
825 /// if let Ok(mut child) = command.spawn() {
826 /// child.wait().expect("command wasn't running");
827 /// println!("Child has finished its execution!");
829 /// println!("ls command didn't start");
832 #[stable(feature = "process", since = "1.0.0")]
833 pub fn wait(&mut self) -> io::Result<ExitStatus> {
834 drop(self.stdin.take());
835 self.handle.wait().map(ExitStatus)
838 /// Attempts to collect the exit status of the child if it has already
841 /// This function will not block the calling thread and will only advisorily
842 /// check to see if the child process has exited or not. If the child has
843 /// exited then on Unix the process id is reaped. This function is
844 /// guaranteed to repeatedly return a successful exit status so long as the
845 /// child has already exited.
847 /// If the child has exited, then `Ok(status)` is returned. If the exit
848 /// status is not available at this time then an error is returned with the
849 /// error kind `WouldBlock`. If an error occurs, then that error is returned.
851 /// Note that unlike `wait`, this function will not attempt to drop stdin.
858 /// #![feature(process_try_wait)]
861 /// use std::process::Command;
863 /// let mut child = Command::new("ls").spawn().unwrap();
865 /// match child.try_wait() {
866 /// Ok(status) => println!("exited with: {}", status),
867 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
868 /// println!("status not ready yet, let's really wait");
869 /// let res = child.wait();
870 /// println!("result: {:?}", res);
872 /// Err(e) => println!("error attempting to wait: {}", e),
875 #[unstable(feature = "process_try_wait", issue = "38903")]
876 pub fn try_wait(&mut self) -> io::Result<ExitStatus> {
877 self.handle.try_wait().map(ExitStatus)
880 /// Simultaneously waits for the child to exit and collect all remaining
881 /// output on the stdout/stderr handles, returning an `Output`
884 /// The stdin handle to the child process, if any, will be closed
885 /// before waiting. This helps avoid deadlock: it ensures that the
886 /// child does not block waiting for input from the parent, while
887 /// the parent waits for the child to exit.
889 /// By default, stdin, stdout and stderr are inherited from the parent.
890 /// In order to capture the output into this `Result<Output>` it is
891 /// necessary to create new pipes between parent and child. Use
892 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
897 /// use std::process::{Command, Stdio};
899 /// let child = Command::new("/bin/cat")
901 /// .stdout(Stdio::piped())
903 /// .expect("failed to execute child");
905 /// let output = child
906 /// .wait_with_output()
907 /// .expect("failed to wait on child");
909 /// assert!(output.status.success());
912 #[stable(feature = "process", since = "1.0.0")]
913 pub fn wait_with_output(mut self) -> io::Result<Output> {
914 drop(self.stdin.take());
916 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
917 match (self.stdout.take(), self.stderr.take()) {
919 (Some(mut out), None) => {
920 let res = out.read_to_end(&mut stdout);
923 (None, Some(mut err)) => {
924 let res = err.read_to_end(&mut stderr);
927 (Some(out), Some(err)) => {
928 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
933 let status = self.wait()?;
942 /// Terminates the current process with the specified exit code.
944 /// This function will never return and will immediately terminate the current
945 /// process. The exit code is passed through to the underlying OS and will be
946 /// available for consumption by another process.
948 /// Note that because this function never returns, and that it terminates the
949 /// process, no destructors on the current stack or any other thread's stack
950 /// will be run. If a clean shutdown is needed it is recommended to only call
951 /// this function at a known point where there are no more destructors left
954 /// ## Platform-specific behavior
956 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
957 /// will be visible to a parent process inspecting the exit code. On most
958 /// Unix-like platforms, only the eight least-significant bits are considered.
962 /// Due to this function’s behavior regarding destructors, a conventional way
963 /// to use the function is to extract the actual computation to another
964 /// function and compute the exit code from its return value:
967 /// use std::io::{self, Write};
969 /// fn run_app() -> Result<(), ()> {
970 /// // Application logic here
975 /// ::std::process::exit(match run_app() {
978 /// writeln!(io::stderr(), "error: {:?}", err).unwrap();
985 /// Due to [platform-specific behavior], the exit code for this example will be
986 /// `0` on Linux, but `256` on Windows:
989 /// use std::process;
991 /// process::exit(0x0f00);
994 /// [platform-specific behavior]: #platform-specific-behavior
995 #[stable(feature = "rust1", since = "1.0.0")]
996 pub fn exit(code: i32) -> ! {
997 ::sys_common::cleanup();
998 ::sys::os::exit(code)
1001 /// Terminates the process in an abnormal fashion.
1003 /// The function will never return and will immediately terminate the current
1004 /// process in a platform specific "abnormal" manner.
1006 /// Note that because this function never returns, and that it terminates the
1007 /// process, no destructors on the current stack or any other thread's stack
1008 /// will be run. If a clean shutdown is needed it is recommended to only call
1009 /// this function at a known point where there are no more destructors left
1011 #[unstable(feature = "process_abort", issue = "37838")]
1012 pub fn abort() -> ! {
1013 unsafe { ::sys::abort_internal() };
1016 #[cfg(all(test, not(target_os = "emscripten")))]
1022 use super::{Command, Output, Stdio};
1024 // FIXME(#10380) these tests should not all be ignored on android.
1027 #[cfg_attr(target_os = "android", ignore)]
1029 let p = if cfg!(target_os = "windows") {
1030 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1032 Command::new("true").spawn()
1035 let mut p = p.unwrap();
1036 assert!(p.wait().unwrap().success());
1040 #[cfg_attr(target_os = "android", ignore)]
1041 fn smoke_failure() {
1042 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1049 #[cfg_attr(target_os = "android", ignore)]
1050 fn exit_reported_right() {
1051 let p = if cfg!(target_os = "windows") {
1052 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1054 Command::new("false").spawn()
1057 let mut p = p.unwrap();
1058 assert!(p.wait().unwrap().code() == Some(1));
1064 #[cfg_attr(target_os = "android", ignore)]
1065 fn signal_reported_right() {
1066 use os::unix::process::ExitStatusExt;
1068 let mut p = Command::new("/bin/sh")
1069 .arg("-c").arg("read a")
1070 .stdin(Stdio::piped())
1073 match p.wait().unwrap().signal() {
1075 result => panic!("not terminated by signal 9 (instead, {:?})",
1080 pub fn run_output(mut cmd: Command) -> String {
1081 let p = cmd.spawn();
1083 let mut p = p.unwrap();
1084 assert!(p.stdout.is_some());
1085 let mut ret = String::new();
1086 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1087 assert!(p.wait().unwrap().success());
1092 #[cfg_attr(target_os = "android", ignore)]
1094 if cfg!(target_os = "windows") {
1095 let mut cmd = Command::new("cmd");
1096 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1097 assert_eq!(run_output(cmd), "foobar\r\n");
1099 let mut cmd = Command::new("echo");
1100 cmd.arg("foobar").stdout(Stdio::piped());
1101 assert_eq!(run_output(cmd), "foobar\n");
1106 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1107 fn set_current_dir_works() {
1108 let mut cmd = Command::new("/bin/sh");
1109 cmd.arg("-c").arg("pwd")
1111 .stdout(Stdio::piped());
1112 assert_eq!(run_output(cmd), "/\n");
1116 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1118 let mut p = Command::new("/bin/sh")
1119 .arg("-c").arg("read line; echo $line")
1120 .stdin(Stdio::piped())
1121 .stdout(Stdio::piped())
1123 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1124 drop(p.stdin.take());
1125 let mut out = String::new();
1126 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1127 assert!(p.wait().unwrap().success());
1128 assert_eq!(out, "foobar\n");
1133 #[cfg_attr(target_os = "android", ignore)]
1136 use os::unix::prelude::*;
1138 let mut p = Command::new("/bin/sh")
1139 .arg("-c").arg("true")
1140 .uid(unsafe { libc::getuid() })
1141 .gid(unsafe { libc::getgid() })
1143 assert!(p.wait().unwrap().success());
1147 #[cfg_attr(target_os = "android", ignore)]
1149 fn uid_to_root_fails() {
1150 use os::unix::prelude::*;
1153 // if we're already root, this isn't a valid test. Most of the bots run
1154 // as non-root though (android is an exception).
1155 if unsafe { libc::getuid() == 0 } { return }
1156 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1160 #[cfg_attr(target_os = "android", ignore)]
1161 fn test_process_status() {
1162 let mut status = if cfg!(target_os = "windows") {
1163 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1165 Command::new("false").status().unwrap()
1167 assert!(status.code() == Some(1));
1169 status = if cfg!(target_os = "windows") {
1170 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1172 Command::new("true").status().unwrap()
1174 assert!(status.success());
1178 fn test_process_output_fail_to_start() {
1179 match Command::new("/no-binary-by-this-name-should-exist").output() {
1180 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1186 #[cfg_attr(target_os = "android", ignore)]
1187 fn test_process_output_output() {
1188 let Output {status, stdout, stderr}
1189 = if cfg!(target_os = "windows") {
1190 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1192 Command::new("echo").arg("hello").output().unwrap()
1194 let output_str = str::from_utf8(&stdout).unwrap();
1196 assert!(status.success());
1197 assert_eq!(output_str.trim().to_string(), "hello");
1198 assert_eq!(stderr, Vec::new());
1202 #[cfg_attr(target_os = "android", ignore)]
1203 fn test_process_output_error() {
1204 let Output {status, stdout, stderr}
1205 = if cfg!(target_os = "windows") {
1206 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1208 Command::new("mkdir").arg(".").output().unwrap()
1211 assert!(status.code() == Some(1));
1212 assert_eq!(stdout, Vec::new());
1213 assert!(!stderr.is_empty());
1217 #[cfg_attr(target_os = "android", ignore)]
1218 fn test_finish_once() {
1219 let mut prog = if cfg!(target_os = "windows") {
1220 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1222 Command::new("false").spawn().unwrap()
1224 assert!(prog.wait().unwrap().code() == Some(1));
1228 #[cfg_attr(target_os = "android", ignore)]
1229 fn test_finish_twice() {
1230 let mut prog = if cfg!(target_os = "windows") {
1231 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1233 Command::new("false").spawn().unwrap()
1235 assert!(prog.wait().unwrap().code() == Some(1));
1236 assert!(prog.wait().unwrap().code() == Some(1));
1240 #[cfg_attr(target_os = "android", ignore)]
1241 fn test_wait_with_output_once() {
1242 let prog = if cfg!(target_os = "windows") {
1243 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1245 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1248 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1249 let output_str = str::from_utf8(&stdout).unwrap();
1251 assert!(status.success());
1252 assert_eq!(output_str.trim().to_string(), "hello");
1253 assert_eq!(stderr, Vec::new());
1256 #[cfg(all(unix, not(target_os="android")))]
1257 pub fn env_cmd() -> Command {
1260 #[cfg(target_os="android")]
1261 pub fn env_cmd() -> Command {
1262 let mut cmd = Command::new("/system/bin/sh");
1263 cmd.arg("-c").arg("set");
1268 pub fn env_cmd() -> Command {
1269 let mut cmd = Command::new("cmd");
1270 cmd.arg("/c").arg("set");
1275 fn test_inherit_env() {
1278 let result = env_cmd().output().unwrap();
1279 let output = String::from_utf8(result.stdout).unwrap();
1281 for (ref k, ref v) in env::vars() {
1282 // don't check android RANDOM variables
1283 if cfg!(target_os = "android") && *k == "RANDOM" {
1287 // Windows has hidden environment variables whose names start with
1288 // equals signs (`=`). Those do not show up in the output of the
1290 assert!((cfg!(windows) && k.starts_with("=")) ||
1291 k.starts_with("DYLD") ||
1292 output.contains(&format!("{}={}", *k, *v)) ||
1293 output.contains(&format!("{}='{}'", *k, *v)),
1294 "output doesn't contain `{}={}`\n{}",
1300 fn test_override_env() {
1303 // In some build environments (such as chrooted Nix builds), `env` can
1304 // only be found in the explicitly-provided PATH env variable, not in
1305 // default places such as /bin or /usr/bin. So we need to pass through
1306 // PATH to our sub-process.
1307 let mut cmd = env_cmd();
1308 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1309 if let Some(p) = env::var_os("PATH") {
1310 cmd.env("PATH", &p);
1312 let result = cmd.output().unwrap();
1313 let output = String::from_utf8_lossy(&result.stdout).to_string();
1315 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1316 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1320 fn test_add_to_env() {
1321 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1322 let output = String::from_utf8_lossy(&result.stdout).to_string();
1324 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1325 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1328 // Regression tests for #30858.
1330 fn test_interior_nul_in_progname_is_error() {
1331 match Command::new("has-some-\0\0s-inside").spawn() {
1332 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1338 fn test_interior_nul_in_arg_is_error() {
1339 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1340 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1346 fn test_interior_nul_in_args_is_error() {
1347 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1348 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1354 fn test_interior_nul_in_current_dir_is_error() {
1355 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1356 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1361 // Regression tests for #30862.
1363 fn test_interior_nul_in_env_key_is_error() {
1364 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1365 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1371 fn test_interior_nul_in_env_value_is_error() {
1372 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1373 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1378 /// Test that process creation flags work by debugging a process.
1379 /// Other creation flags make it hard or impossible to detect
1380 /// behavioral changes in the process.
1383 fn test_creation_flags() {
1384 use os::windows::process::CommandExt;
1385 use sys::c::{BOOL, DWORD, INFINITE};
1387 struct DEBUG_EVENT {
1388 pub event_code: DWORD,
1389 pub process_id: DWORD,
1390 pub thread_id: DWORD,
1391 // This is a union in the real struct, but we don't
1392 // need this data for the purposes of this test.
1393 pub _junk: [u8; 164],
1397 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1398 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1399 dwContinueStatus: DWORD) -> BOOL;
1402 const DEBUG_PROCESS: DWORD = 1;
1403 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1404 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1406 let mut child = Command::new("cmd")
1407 .creation_flags(DEBUG_PROCESS)
1408 .stdin(Stdio::piped()).spawn().unwrap();
1409 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1411 let mut event = DEBUG_EVENT {
1418 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1419 panic!("WaitForDebugEvent failed!");
1423 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1427 if unsafe { ContinueDebugEvent(event.process_id,
1429 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1430 panic!("ContinueDebugEvent failed!");
1433 assert!(events > 0);