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(Some(status))` is returned. If the
848 /// exit status is not available at this time then `Ok(None)` is returned.
849 /// 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)]
860 /// use std::process::Command;
862 /// let mut child = Command::new("ls").spawn().unwrap();
864 /// match child.try_wait() {
865 /// Ok(Some(status)) => println!("exited with: {}", status),
867 /// println!("status not ready yet, let's really wait");
868 /// let res = child.wait();
869 /// println!("result: {:?}", res);
871 /// Err(e) => println!("error attempting to wait: {}", e),
874 #[unstable(feature = "process_try_wait", issue = "38903")]
875 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
876 Ok(self.handle.try_wait()?.map(ExitStatus))
879 /// Simultaneously waits for the child to exit and collect all remaining
880 /// output on the stdout/stderr handles, returning an `Output`
883 /// The stdin handle to the child process, if any, will be closed
884 /// before waiting. This helps avoid deadlock: it ensures that the
885 /// child does not block waiting for input from the parent, while
886 /// the parent waits for the child to exit.
888 /// By default, stdin, stdout and stderr are inherited from the parent.
889 /// In order to capture the output into this `Result<Output>` it is
890 /// necessary to create new pipes between parent and child. Use
891 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
896 /// use std::process::{Command, Stdio};
898 /// let child = Command::new("/bin/cat")
900 /// .stdout(Stdio::piped())
902 /// .expect("failed to execute child");
904 /// let output = child
905 /// .wait_with_output()
906 /// .expect("failed to wait on child");
908 /// assert!(output.status.success());
911 #[stable(feature = "process", since = "1.0.0")]
912 pub fn wait_with_output(mut self) -> io::Result<Output> {
913 drop(self.stdin.take());
915 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
916 match (self.stdout.take(), self.stderr.take()) {
918 (Some(mut out), None) => {
919 let res = out.read_to_end(&mut stdout);
922 (None, Some(mut err)) => {
923 let res = err.read_to_end(&mut stderr);
926 (Some(out), Some(err)) => {
927 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
932 let status = self.wait()?;
941 /// Terminates the current process with the specified exit code.
943 /// This function will never return and will immediately terminate the current
944 /// process. The exit code is passed through to the underlying OS and will be
945 /// available for consumption by another process.
947 /// Note that because this function never returns, and that it terminates the
948 /// process, no destructors on the current stack or any other thread's stack
949 /// will be run. If a clean shutdown is needed it is recommended to only call
950 /// this function at a known point where there are no more destructors left
953 /// ## Platform-specific behavior
955 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
956 /// will be visible to a parent process inspecting the exit code. On most
957 /// Unix-like platforms, only the eight least-significant bits are considered.
961 /// Due to this function’s behavior regarding destructors, a conventional way
962 /// to use the function is to extract the actual computation to another
963 /// function and compute the exit code from its return value:
966 /// use std::io::{self, Write};
968 /// fn run_app() -> Result<(), ()> {
969 /// // Application logic here
974 /// ::std::process::exit(match run_app() {
977 /// writeln!(io::stderr(), "error: {:?}", err).unwrap();
984 /// Due to [platform-specific behavior], the exit code for this example will be
985 /// `0` on Linux, but `256` on Windows:
988 /// use std::process;
990 /// process::exit(0x0f00);
993 /// [platform-specific behavior]: #platform-specific-behavior
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn exit(code: i32) -> ! {
996 ::sys_common::cleanup();
997 ::sys::os::exit(code)
1000 /// Terminates the process in an abnormal fashion.
1002 /// The function will never return and will immediately terminate the current
1003 /// process in a platform specific "abnormal" manner.
1005 /// Note that because this function never returns, and that it terminates the
1006 /// process, no destructors on the current stack or any other thread's stack
1007 /// will be run. If a clean shutdown is needed it is recommended to only call
1008 /// this function at a known point where there are no more destructors left
1010 #[unstable(feature = "process_abort", issue = "37838")]
1011 pub fn abort() -> ! {
1012 unsafe { ::sys::abort_internal() };
1015 #[cfg(all(test, not(target_os = "emscripten")))]
1021 use super::{Command, Output, Stdio};
1023 // FIXME(#10380) these tests should not all be ignored on android.
1026 #[cfg_attr(target_os = "android", ignore)]
1028 let p = if cfg!(target_os = "windows") {
1029 Command::new("cmd").args(&["/C", "exit 0"]).spawn()
1031 Command::new("true").spawn()
1034 let mut p = p.unwrap();
1035 assert!(p.wait().unwrap().success());
1039 #[cfg_attr(target_os = "android", ignore)]
1040 fn smoke_failure() {
1041 match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
1048 #[cfg_attr(target_os = "android", ignore)]
1049 fn exit_reported_right() {
1050 let p = if cfg!(target_os = "windows") {
1051 Command::new("cmd").args(&["/C", "exit 1"]).spawn()
1053 Command::new("false").spawn()
1056 let mut p = p.unwrap();
1057 assert!(p.wait().unwrap().code() == Some(1));
1063 #[cfg_attr(target_os = "android", ignore)]
1064 fn signal_reported_right() {
1065 use os::unix::process::ExitStatusExt;
1067 let mut p = Command::new("/bin/sh")
1068 .arg("-c").arg("read a")
1069 .stdin(Stdio::piped())
1072 match p.wait().unwrap().signal() {
1074 result => panic!("not terminated by signal 9 (instead, {:?})",
1079 pub fn run_output(mut cmd: Command) -> String {
1080 let p = cmd.spawn();
1082 let mut p = p.unwrap();
1083 assert!(p.stdout.is_some());
1084 let mut ret = String::new();
1085 p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
1086 assert!(p.wait().unwrap().success());
1091 #[cfg_attr(target_os = "android", ignore)]
1093 if cfg!(target_os = "windows") {
1094 let mut cmd = Command::new("cmd");
1095 cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
1096 assert_eq!(run_output(cmd), "foobar\r\n");
1098 let mut cmd = Command::new("echo");
1099 cmd.arg("foobar").stdout(Stdio::piped());
1100 assert_eq!(run_output(cmd), "foobar\n");
1105 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1106 fn set_current_dir_works() {
1107 let mut cmd = Command::new("/bin/sh");
1108 cmd.arg("-c").arg("pwd")
1110 .stdout(Stdio::piped());
1111 assert_eq!(run_output(cmd), "/\n");
1115 #[cfg_attr(any(windows, target_os = "android"), ignore)]
1117 let mut p = Command::new("/bin/sh")
1118 .arg("-c").arg("read line; echo $line")
1119 .stdin(Stdio::piped())
1120 .stdout(Stdio::piped())
1122 p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
1123 drop(p.stdin.take());
1124 let mut out = String::new();
1125 p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
1126 assert!(p.wait().unwrap().success());
1127 assert_eq!(out, "foobar\n");
1132 #[cfg_attr(target_os = "android", ignore)]
1135 use os::unix::prelude::*;
1137 let mut p = Command::new("/bin/sh")
1138 .arg("-c").arg("true")
1139 .uid(unsafe { libc::getuid() })
1140 .gid(unsafe { libc::getgid() })
1142 assert!(p.wait().unwrap().success());
1146 #[cfg_attr(target_os = "android", ignore)]
1148 fn uid_to_root_fails() {
1149 use os::unix::prelude::*;
1152 // if we're already root, this isn't a valid test. Most of the bots run
1153 // as non-root though (android is an exception).
1154 if unsafe { libc::getuid() == 0 } { return }
1155 assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
1159 #[cfg_attr(target_os = "android", ignore)]
1160 fn test_process_status() {
1161 let mut status = if cfg!(target_os = "windows") {
1162 Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
1164 Command::new("false").status().unwrap()
1166 assert!(status.code() == Some(1));
1168 status = if cfg!(target_os = "windows") {
1169 Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
1171 Command::new("true").status().unwrap()
1173 assert!(status.success());
1177 fn test_process_output_fail_to_start() {
1178 match Command::new("/no-binary-by-this-name-should-exist").output() {
1179 Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
1185 #[cfg_attr(target_os = "android", ignore)]
1186 fn test_process_output_output() {
1187 let Output {status, stdout, stderr}
1188 = if cfg!(target_os = "windows") {
1189 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
1191 Command::new("echo").arg("hello").output().unwrap()
1193 let output_str = str::from_utf8(&stdout).unwrap();
1195 assert!(status.success());
1196 assert_eq!(output_str.trim().to_string(), "hello");
1197 assert_eq!(stderr, Vec::new());
1201 #[cfg_attr(target_os = "android", ignore)]
1202 fn test_process_output_error() {
1203 let Output {status, stdout, stderr}
1204 = if cfg!(target_os = "windows") {
1205 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
1207 Command::new("mkdir").arg(".").output().unwrap()
1210 assert!(status.code() == Some(1));
1211 assert_eq!(stdout, Vec::new());
1212 assert!(!stderr.is_empty());
1216 #[cfg_attr(target_os = "android", ignore)]
1217 fn test_finish_once() {
1218 let mut prog = if cfg!(target_os = "windows") {
1219 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1221 Command::new("false").spawn().unwrap()
1223 assert!(prog.wait().unwrap().code() == Some(1));
1227 #[cfg_attr(target_os = "android", ignore)]
1228 fn test_finish_twice() {
1229 let mut prog = if cfg!(target_os = "windows") {
1230 Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
1232 Command::new("false").spawn().unwrap()
1234 assert!(prog.wait().unwrap().code() == Some(1));
1235 assert!(prog.wait().unwrap().code() == Some(1));
1239 #[cfg_attr(target_os = "android", ignore)]
1240 fn test_wait_with_output_once() {
1241 let prog = if cfg!(target_os = "windows") {
1242 Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
1244 Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
1247 let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
1248 let output_str = str::from_utf8(&stdout).unwrap();
1250 assert!(status.success());
1251 assert_eq!(output_str.trim().to_string(), "hello");
1252 assert_eq!(stderr, Vec::new());
1255 #[cfg(all(unix, not(target_os="android")))]
1256 pub fn env_cmd() -> Command {
1259 #[cfg(target_os="android")]
1260 pub fn env_cmd() -> Command {
1261 let mut cmd = Command::new("/system/bin/sh");
1262 cmd.arg("-c").arg("set");
1267 pub fn env_cmd() -> Command {
1268 let mut cmd = Command::new("cmd");
1269 cmd.arg("/c").arg("set");
1274 fn test_inherit_env() {
1277 let result = env_cmd().output().unwrap();
1278 let output = String::from_utf8(result.stdout).unwrap();
1280 for (ref k, ref v) in env::vars() {
1281 // don't check android RANDOM variables
1282 if cfg!(target_os = "android") && *k == "RANDOM" {
1286 // Windows has hidden environment variables whose names start with
1287 // equals signs (`=`). Those do not show up in the output of the
1289 assert!((cfg!(windows) && k.starts_with("=")) ||
1290 k.starts_with("DYLD") ||
1291 output.contains(&format!("{}={}", *k, *v)) ||
1292 output.contains(&format!("{}='{}'", *k, *v)),
1293 "output doesn't contain `{}={}`\n{}",
1299 fn test_override_env() {
1302 // In some build environments (such as chrooted Nix builds), `env` can
1303 // only be found in the explicitly-provided PATH env variable, not in
1304 // default places such as /bin or /usr/bin. So we need to pass through
1305 // PATH to our sub-process.
1306 let mut cmd = env_cmd();
1307 cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
1308 if let Some(p) = env::var_os("PATH") {
1309 cmd.env("PATH", &p);
1311 let result = cmd.output().unwrap();
1312 let output = String::from_utf8_lossy(&result.stdout).to_string();
1314 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1315 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1319 fn test_add_to_env() {
1320 let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
1321 let output = String::from_utf8_lossy(&result.stdout).to_string();
1323 assert!(output.contains("RUN_TEST_NEW_ENV=123"),
1324 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
1327 // Regression tests for #30858.
1329 fn test_interior_nul_in_progname_is_error() {
1330 match Command::new("has-some-\0\0s-inside").spawn() {
1331 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1337 fn test_interior_nul_in_arg_is_error() {
1338 match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
1339 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1345 fn test_interior_nul_in_args_is_error() {
1346 match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
1347 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1353 fn test_interior_nul_in_current_dir_is_error() {
1354 match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
1355 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1360 // Regression tests for #30862.
1362 fn test_interior_nul_in_env_key_is_error() {
1363 match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
1364 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1370 fn test_interior_nul_in_env_value_is_error() {
1371 match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
1372 Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
1377 /// Test that process creation flags work by debugging a process.
1378 /// Other creation flags make it hard or impossible to detect
1379 /// behavioral changes in the process.
1382 fn test_creation_flags() {
1383 use os::windows::process::CommandExt;
1384 use sys::c::{BOOL, DWORD, INFINITE};
1386 struct DEBUG_EVENT {
1387 pub event_code: DWORD,
1388 pub process_id: DWORD,
1389 pub thread_id: DWORD,
1390 // This is a union in the real struct, but we don't
1391 // need this data for the purposes of this test.
1392 pub _junk: [u8; 164],
1396 fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
1397 fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
1398 dwContinueStatus: DWORD) -> BOOL;
1401 const DEBUG_PROCESS: DWORD = 1;
1402 const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
1403 const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;
1405 let mut child = Command::new("cmd")
1406 .creation_flags(DEBUG_PROCESS)
1407 .stdin(Stdio::piped()).spawn().unwrap();
1408 child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
1410 let mut event = DEBUG_EVENT {
1417 if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
1418 panic!("WaitForDebugEvent failed!");
1422 if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
1426 if unsafe { ContinueDebugEvent(event.process_id,
1428 DBG_EXCEPTION_NOT_HANDLED) } == 0 {
1429 panic!("ContinueDebugEvent failed!");
1432 assert!(events > 0);