1 //! A module for working with processes.
2 //!
3 //! This module is mostly concerned with spawning and interacting with child
4 //! processes, but it also provides [`abort`] and [`exit`] for terminating the
5 //! current process.
6 //!
7 //! # Spawning a process
8 //!
9 //! The [`Command`] struct is used to configure and spawn processes:
10 //!
11 //! ```no_run
12 //! use std::process::Command;
13 //!
14 //! let output = Command::new("echo")
15 //! .arg("Hello world")
16 //! .output()
17 //! .expect("Failed to execute command");
18 //!
19 //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
20 //! ```
21 //!
22 //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
23 //! to spawn a process. In particular, [`output`] spawns the child process and
24 //! waits until the process terminates, while [`spawn`] will return a [`Child`]
25 //! that represents the spawned child process.
26 //!
27 //! # Handling I/O
28 //!
29 //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
30 //! configured by passing an [`Stdio`] to the corresponding method on
31 //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
32 //! example, piping output from one command into another command can be done
33 //! like so:
34 //!
35 //! ```no_run
36 //! use std::process::{Command, Stdio};
37 //!
38 //! // stdout must be configured with `Stdio::piped` in order to use
39 //! // `echo_child.stdout`
40 //! let echo_child = Command::new("echo")
41 //! .arg("Oh no, a tpyo!")
42 //! .stdout(Stdio::piped())
43 //! .spawn()
44 //! .expect("Failed to start echo process");
45 //!
46 //! // Note that `echo_child` is moved here, but we won't be needing
47 //! // `echo_child` anymore
48 //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
49 //!
50 //! let mut sed_child = Command::new("sed")
51 //! .arg("s/tpyo/typo/")
52 //! .stdin(Stdio::from(echo_out))
53 //! .stdout(Stdio::piped())
54 //! .spawn()
55 //! .expect("Failed to start sed process");
56 //!
57 //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
58 //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
59 //! ```
60 //!
61 //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
62 //! [`ChildStdin`] implements [`Write`]:
63 //!
64 //! ```no_run
65 //! use std::process::{Command, Stdio};
66 //! use std::io::Write;
67 //!
68 //! let mut child = Command::new("/bin/cat")
69 //! .stdin(Stdio::piped())
70 //! .stdout(Stdio::piped())
71 //! .spawn()
72 //! .expect("failed to execute child");
73 //!
74 //! // If the child process fills its stdout buffer, it may end up
75 //! // waiting until the parent reads the stdout, and not be able to
76 //! // read stdin in the meantime, causing a deadlock.
77 //! // Writing from another thread ensures that stdout is being read
78 //! // at the same time, avoiding the problem.
79 //! let mut stdin = child.stdin.take().expect("failed to get stdin");
80 //! std::thread::spawn(move || {
81 //! stdin.write_all(b"test").expect("failed to write to stdin");
82 //! });
83 //!
84 //! let output = child
85 //! .wait_with_output()
86 //! .expect("failed to wait on child");
87 //!
88 //! assert_eq!(b"test", output.stdout.as_slice());
89 //! ```
90 //!
91 //! # Windows argument splitting
92 //!
93 //! On Unix systems arguments are passed to a new process as an array of strings
94 //! but on Windows arguments are passed as a single commandline string and it's
95 //! up to the child process to parse it into an array. Therefore the parent and
96 //! child processes must agree on how the commandline string is encoded.
97 //!
98 //! Most programs use the standard C run-time `argv`, which in practice results
99 //! in consistent argument handling. However some programs have their own way of
100 //! parsing the commandline string. In these cases using [`arg`] or [`args`] may
101 //! result in the child process seeing a different array of arguments then the
102 //! parent process intended.
103 //!
104 //! Two ways of mitigating this are:
105 //!
106 //! * Validate untrusted input so that only a safe subset is allowed.
107 //! * Use [`raw_arg`] to build a custom commandline. This bypasses the escaping
108 //! rules used by [`arg`] so should be used with due caution.
109 //!
110 //! `cmd.exe` and `.bat` use non-standard argument parsing and are especially
111 //! vulnerable to malicious input as they may be used to run arbitrary shell
112 //! commands. Untrusted arguments should be restricted as much as possible.
113 //! For examples on handling this see [`raw_arg`].
114 //!
115 //! ### Bat file special handling
116 //!
117 //! On Windows, `Command` uses the Windows API function [`CreateProcessW`] to
118 //! spawn new processes. An undocumented feature of this function is that,
119 //! when given a `.bat` file as the application to run, it will automatically
120 //! convert that into running `cmd.exe /c` with the bat file as the next argument.
121 //!
122 //! For historical reasons Rust currently preserves this behaviour when using
123 //! [`Command::new`], and escapes the arguments according to `cmd.exe` rules.
124 //! Due to the complexity of `cmd.exe` argument handling, it might not be
125 //! possible to safely escape some special chars, and using them will result
126 //! in an error being returned at process spawn. The set of unescapeable
127 //! special chars might change between releases.
128 //!
129 //! Also note that running `.bat` scripts in this way may be removed in the
130 //! future and so should not be relied upon.
131 //!
132 //! [`spawn`]: Command::spawn
133 //! [`output`]: Command::output
134 //!
135 //! [`stdout`]: Command::stdout
136 //! [`stdin`]: Command::stdin
137 //! [`stderr`]: Command::stderr
138 //!
139 //! [`Write`]: io::Write
140 //! [`Read`]: io::Read
141 //!
142 //! [`arg`]: Command::arg
143 //! [`args`]: Command::args
144 //! [`raw_arg`]: crate::os::windows::process::CommandExt::raw_arg
145 //!
146 //! [`CreateProcessW`]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
147
148 #![stable(feature = "process", since = "1.0.0")]
149 #![deny(unsafe_op_in_unsafe_fn)]
150
151 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
152 mod tests;
153
154 use crate::io::prelude::*;
155
156 use crate::convert::Infallible;
157 use crate::ffi::OsStr;
158 use crate::fmt;
159 use crate::fs;
160 use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
161 use crate::num::NonZeroI32;
162 use crate::path::Path;
163 use crate::str;
164 use crate::sys::pipe::{read2, AnonPipe};
165 use crate::sys::process as imp;
166 #[stable(feature = "command_access", since = "1.57.0")]
167 pub use crate::sys_common::process::CommandEnvs;
168 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
169
170 /// Representation of a running or exited child process.
171 ///
172 /// This structure is used to represent and manage child processes. A child
173 /// process is created via the [`Command`] struct, which configures the
174 /// spawning process and can itself be constructed using a builder-style
175 /// interface.
176 ///
177 /// There is no implementation of [`Drop`] for child processes,
178 /// so if you do not ensure the `Child` has exited then it will continue to
179 /// run, even after the `Child` handle to the child process has gone out of
180 /// scope.
181 ///
182 /// Calling [`wait`] (or other functions that wrap around it) will make
183 /// the parent process wait until the child has actually exited before
184 /// continuing.
185 ///
186 /// # Warning
187 ///
188 /// On some systems, calling [`wait`] or similar is necessary for the OS to
189 /// release resources. A process that terminated but has not been waited on is
190 /// still around as a "zombie". Leaving too many zombies around may exhaust
191 /// global resources (for example process IDs).
192 ///
193 /// The standard library does *not* automatically wait on child processes (not
194 /// even if the `Child` is dropped), it is up to the application developer to do
195 /// so. As a consequence, dropping `Child` handles without waiting on them first
196 /// is not recommended in long-running applications.
197 ///
198 /// # Examples
199 ///
200 /// ```should_panic
201 /// use std::process::Command;
202 ///
203 /// let mut child = Command::new("/bin/cat")
204 /// .arg("file.txt")
205 /// .spawn()
206 /// .expect("failed to execute child");
207 ///
208 /// let ecode = child.wait()
209 /// .expect("failed to wait on child");
210 ///
211 /// assert!(ecode.success());
212 /// ```
213 ///
214 /// [`wait`]: Child::wait
215 #[stable(feature = "process", since = "1.0.0")]
216 pub struct Child {
217 pub(crate) handle: imp::Process,
218
219 /// The handle for writing to the child's standard input (stdin), if it
220 /// has been captured. You might find it helpful to do
221 ///
222 /// ```compile_fail,E0425
223 /// let stdin = child.stdin.take().unwrap();
224 /// ```
225 ///
226 /// to avoid partially moving the `child` and thus blocking yourself from calling
227 /// functions on `child` while using `stdin`.
228 #[stable(feature = "process", since = "1.0.0")]
229 pub stdin: Option<ChildStdin>,
230
231 /// The handle for reading from the child's standard output (stdout), if it
232 /// has been captured. You might find it helpful to do
233 ///
234 /// ```compile_fail,E0425
235 /// let stdout = child.stdout.take().unwrap();
236 /// ```
237 ///
238 /// to avoid partially moving the `child` and thus blocking yourself from calling
239 /// functions on `child` while using `stdout`.
240 #[stable(feature = "process", since = "1.0.0")]
241 pub stdout: Option<ChildStdout>,
242
243 /// The handle for reading from the child's standard error (stderr), if it
244 /// has been captured. You might find it helpful to do
245 ///
246 /// ```compile_fail,E0425
247 /// let stderr = child.stderr.take().unwrap();
248 /// ```
249 ///
250 /// to avoid partially moving the `child` and thus blocking yourself from calling
251 /// functions on `child` while using `stderr`.
252 #[stable(feature = "process", since = "1.0.0")]
253 pub stderr: Option<ChildStderr>,
254 }
255
256 /// Allows extension traits within `std`.
257 #[unstable(feature = "sealed", issue = "none")]
258 impl crate::sealed::Sealed for Child {}
259
260 impl AsInner<imp::Process> for Child {
261 #[inline]
as_inner(&self) -> &imp::Process262 fn as_inner(&self) -> &imp::Process {
263 &self.handle
264 }
265 }
266
267 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child268 fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
269 Child {
270 handle,
271 stdin: io.stdin.map(ChildStdin::from_inner),
272 stdout: io.stdout.map(ChildStdout::from_inner),
273 stderr: io.stderr.map(ChildStderr::from_inner),
274 }
275 }
276 }
277
278 impl IntoInner<imp::Process> for Child {
into_inner(self) -> imp::Process279 fn into_inner(self) -> imp::Process {
280 self.handle
281 }
282 }
283
284 #[stable(feature = "std_debug", since = "1.16.0")]
285 impl fmt::Debug for Child {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 f.debug_struct("Child")
288 .field("stdin", &self.stdin)
289 .field("stdout", &self.stdout)
290 .field("stderr", &self.stderr)
291 .finish_non_exhaustive()
292 }
293 }
294
295 /// A handle to a child process's standard input (stdin).
296 ///
297 /// This struct is used in the [`stdin`] field on [`Child`].
298 ///
299 /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
300 /// file handle will be closed. If the child process was blocked on input prior
301 /// to being dropped, it will become unblocked after dropping.
302 ///
303 /// [`stdin`]: Child::stdin
304 /// [dropped]: Drop
305 #[stable(feature = "process", since = "1.0.0")]
306 pub struct ChildStdin {
307 inner: AnonPipe,
308 }
309
310 // In addition to the `impl`s here, `ChildStdin` also has `impl`s for
311 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
312 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
313 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
314 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
315
316 #[stable(feature = "process", since = "1.0.0")]
317 impl Write for ChildStdin {
write(&mut self, buf: &[u8]) -> io::Result<usize>318 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
319 (&*self).write(buf)
320 }
321
write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>322 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
323 (&*self).write_vectored(bufs)
324 }
325
is_write_vectored(&self) -> bool326 fn is_write_vectored(&self) -> bool {
327 io::Write::is_write_vectored(&&*self)
328 }
329
flush(&mut self) -> io::Result<()>330 fn flush(&mut self) -> io::Result<()> {
331 (&*self).flush()
332 }
333 }
334
335 #[stable(feature = "write_mt", since = "1.48.0")]
336 impl Write for &ChildStdin {
write(&mut self, buf: &[u8]) -> io::Result<usize>337 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
338 self.inner.write(buf)
339 }
340
write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>341 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
342 self.inner.write_vectored(bufs)
343 }
344
is_write_vectored(&self) -> bool345 fn is_write_vectored(&self) -> bool {
346 self.inner.is_write_vectored()
347 }
348
flush(&mut self) -> io::Result<()>349 fn flush(&mut self) -> io::Result<()> {
350 Ok(())
351 }
352 }
353
354 impl AsInner<AnonPipe> for ChildStdin {
355 #[inline]
as_inner(&self) -> &AnonPipe356 fn as_inner(&self) -> &AnonPipe {
357 &self.inner
358 }
359 }
360
361 impl IntoInner<AnonPipe> for ChildStdin {
into_inner(self) -> AnonPipe362 fn into_inner(self) -> AnonPipe {
363 self.inner
364 }
365 }
366
367 impl FromInner<AnonPipe> for ChildStdin {
from_inner(pipe: AnonPipe) -> ChildStdin368 fn from_inner(pipe: AnonPipe) -> ChildStdin {
369 ChildStdin { inner: pipe }
370 }
371 }
372
373 #[stable(feature = "std_debug", since = "1.16.0")]
374 impl fmt::Debug for ChildStdin {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 f.debug_struct("ChildStdin").finish_non_exhaustive()
377 }
378 }
379
380 /// A handle to a child process's standard output (stdout).
381 ///
382 /// This struct is used in the [`stdout`] field on [`Child`].
383 ///
384 /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
385 /// underlying file handle will be closed.
386 ///
387 /// [`stdout`]: Child::stdout
388 /// [dropped]: Drop
389 #[stable(feature = "process", since = "1.0.0")]
390 pub struct ChildStdout {
391 inner: AnonPipe,
392 }
393
394 // In addition to the `impl`s here, `ChildStdout` also has `impl`s for
395 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
396 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
397 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
398 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
399
400 #[stable(feature = "process", since = "1.0.0")]
401 impl Read for ChildStdout {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>402 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
403 self.inner.read(buf)
404 }
405
read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()>406 fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
407 self.inner.read_buf(buf)
408 }
409
read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>410 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
411 self.inner.read_vectored(bufs)
412 }
413
414 #[inline]
is_read_vectored(&self) -> bool415 fn is_read_vectored(&self) -> bool {
416 self.inner.is_read_vectored()
417 }
418
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>419 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
420 self.inner.read_to_end(buf)
421 }
422 }
423
424 impl AsInner<AnonPipe> for ChildStdout {
425 #[inline]
as_inner(&self) -> &AnonPipe426 fn as_inner(&self) -> &AnonPipe {
427 &self.inner
428 }
429 }
430
431 impl IntoInner<AnonPipe> for ChildStdout {
into_inner(self) -> AnonPipe432 fn into_inner(self) -> AnonPipe {
433 self.inner
434 }
435 }
436
437 impl FromInner<AnonPipe> for ChildStdout {
from_inner(pipe: AnonPipe) -> ChildStdout438 fn from_inner(pipe: AnonPipe) -> ChildStdout {
439 ChildStdout { inner: pipe }
440 }
441 }
442
443 #[stable(feature = "std_debug", since = "1.16.0")]
444 impl fmt::Debug for ChildStdout {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446 f.debug_struct("ChildStdout").finish_non_exhaustive()
447 }
448 }
449
450 /// A handle to a child process's stderr.
451 ///
452 /// This struct is used in the [`stderr`] field on [`Child`].
453 ///
454 /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
455 /// underlying file handle will be closed.
456 ///
457 /// [`stderr`]: Child::stderr
458 /// [dropped]: Drop
459 #[stable(feature = "process", since = "1.0.0")]
460 pub struct ChildStderr {
461 inner: AnonPipe,
462 }
463
464 // In addition to the `impl`s here, `ChildStderr` also has `impl`s for
465 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
466 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
467 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
468 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
469
470 #[stable(feature = "process", since = "1.0.0")]
471 impl Read for ChildStderr {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>472 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
473 self.inner.read(buf)
474 }
475
read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()>476 fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
477 self.inner.read_buf(buf)
478 }
479
read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>480 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
481 self.inner.read_vectored(bufs)
482 }
483
484 #[inline]
is_read_vectored(&self) -> bool485 fn is_read_vectored(&self) -> bool {
486 self.inner.is_read_vectored()
487 }
488 }
489
490 impl AsInner<AnonPipe> for ChildStderr {
491 #[inline]
as_inner(&self) -> &AnonPipe492 fn as_inner(&self) -> &AnonPipe {
493 &self.inner
494 }
495 }
496
497 impl IntoInner<AnonPipe> for ChildStderr {
into_inner(self) -> AnonPipe498 fn into_inner(self) -> AnonPipe {
499 self.inner
500 }
501 }
502
503 impl FromInner<AnonPipe> for ChildStderr {
from_inner(pipe: AnonPipe) -> ChildStderr504 fn from_inner(pipe: AnonPipe) -> ChildStderr {
505 ChildStderr { inner: pipe }
506 }
507 }
508
509 #[stable(feature = "std_debug", since = "1.16.0")]
510 impl fmt::Debug for ChildStderr {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 f.debug_struct("ChildStderr").finish_non_exhaustive()
513 }
514 }
515
516 /// A process builder, providing fine-grained control
517 /// over how a new process should be spawned.
518 ///
519 /// A default configuration can be
520 /// generated using `Command::new(program)`, where `program` gives a path to the
521 /// program to be executed. Additional builder methods allow the configuration
522 /// to be changed (for example, by adding arguments) prior to spawning:
523 ///
524 /// ```
525 /// use std::process::Command;
526 ///
527 /// let output = if cfg!(target_os = "windows") {
528 /// Command::new("cmd")
529 /// .args(["/C", "echo hello"])
530 /// .output()
531 /// .expect("failed to execute process")
532 /// } else {
533 /// Command::new("sh")
534 /// .arg("-c")
535 /// .arg("echo hello")
536 /// .output()
537 /// .expect("failed to execute process")
538 /// };
539 ///
540 /// let hello = output.stdout;
541 /// ```
542 ///
543 /// `Command` can be reused to spawn multiple processes. The builder methods
544 /// change the command without needing to immediately spawn the process.
545 ///
546 /// ```no_run
547 /// use std::process::Command;
548 ///
549 /// let mut echo_hello = Command::new("sh");
550 /// echo_hello.arg("-c")
551 /// .arg("echo hello");
552 /// let hello_1 = echo_hello.output().expect("failed to execute process");
553 /// let hello_2 = echo_hello.output().expect("failed to execute process");
554 /// ```
555 ///
556 /// Similarly, you can call builder methods after spawning a process and then
557 /// spawn a new process with the modified settings.
558 ///
559 /// ```no_run
560 /// use std::process::Command;
561 ///
562 /// let mut list_dir = Command::new("ls");
563 ///
564 /// // Execute `ls` in the current directory of the program.
565 /// list_dir.status().expect("process failed to execute");
566 ///
567 /// println!();
568 ///
569 /// // Change `ls` to execute in the root directory.
570 /// list_dir.current_dir("/");
571 ///
572 /// // And then execute `ls` again but in the root directory.
573 /// list_dir.status().expect("process failed to execute");
574 /// ```
575 #[stable(feature = "process", since = "1.0.0")]
576 pub struct Command {
577 inner: imp::Command,
578 }
579
580 /// Allows extension traits within `std`.
581 #[unstable(feature = "sealed", issue = "none")]
582 impl crate::sealed::Sealed for Command {}
583
584 impl Command {
585 /// Constructs a new `Command` for launching the program at
586 /// path `program`, with the following default configuration:
587 ///
588 /// * No arguments to the program
589 /// * Inherit the current process's environment
590 /// * Inherit the current process's working directory
591 /// * Inherit stdin/stdout/stderr for [`spawn`] or [`status`], but create pipes for [`output`]
592 ///
593 /// [`spawn`]: Self::spawn
594 /// [`status`]: Self::status
595 /// [`output`]: Self::output
596 ///
597 /// Builder methods are provided to change these defaults and
598 /// otherwise configure the process.
599 ///
600 /// If `program` is not an absolute path, the `PATH` will be searched in
601 /// an OS-defined way.
602 ///
603 /// The search path to be used may be controlled by setting the
604 /// `PATH` environment variable on the Command,
605 /// but this has some implementation limitations on Windows
606 /// (see issue #37519).
607 ///
608 /// # Examples
609 ///
610 /// Basic usage:
611 ///
612 /// ```no_run
613 /// use std::process::Command;
614 ///
615 /// Command::new("sh")
616 /// .spawn()
617 /// .expect("sh command failed to start");
618 /// ```
619 #[stable(feature = "process", since = "1.0.0")]
new<S: AsRef<OsStr>>(program: S) -> Command620 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
621 Command { inner: imp::Command::new(program.as_ref()) }
622 }
623
624 /// Adds an argument to pass to the program.
625 ///
626 /// Only one argument can be passed per use. So instead of:
627 ///
628 /// ```no_run
629 /// # std::process::Command::new("sh")
630 /// .arg("-C /path/to/repo")
631 /// # ;
632 /// ```
633 ///
634 /// usage would be:
635 ///
636 /// ```no_run
637 /// # std::process::Command::new("sh")
638 /// .arg("-C")
639 /// .arg("/path/to/repo")
640 /// # ;
641 /// ```
642 ///
643 /// To pass multiple arguments see [`args`].
644 ///
645 /// [`args`]: Command::args
646 ///
647 /// Note that the argument is not passed through a shell, but given
648 /// literally to the program. This means that shell syntax like quotes,
649 /// escaped characters, word splitting, glob patterns, substitution, etc.
650 /// have no effect.
651 ///
652 /// <div class="warning">
653 ///
654 /// On Windows use caution with untrusted inputs. Most applications use the
655 /// standard convention for decoding arguments passed to them. These are safe to use with `arg`.
656 /// However some applications, such as `cmd.exe` and `.bat` files, use a non-standard way of decoding arguments
657 /// and are therefore vulnerable to malicious input.
658 /// In the case of `cmd.exe` this is especially important because a malicious argument can potentially run arbitrary shell commands.
659 ///
660 /// See [Windows argument splitting][windows-args] for more details
661 /// or [`raw_arg`] for manually implementing non-standard argument encoding.
662 ///
663 /// [`raw_arg`]: crate::os::windows::process::CommandExt::raw_arg
664 /// [windows-args]: crate::process#windows-argument-splitting
665 ///
666 /// </div>
667 ///
668 /// # Examples
669 ///
670 /// Basic usage:
671 ///
672 /// ```no_run
673 /// use std::process::Command;
674 ///
675 /// Command::new("ls")
676 /// .arg("-l")
677 /// .arg("-a")
678 /// .spawn()
679 /// .expect("ls command failed to start");
680 /// ```
681 #[stable(feature = "process", since = "1.0.0")]
arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command682 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
683 self.inner.arg(arg.as_ref());
684 self
685 }
686
687 /// Adds multiple arguments to pass to the program.
688 ///
689 /// To pass a single argument see [`arg`].
690 ///
691 /// [`arg`]: Command::arg
692 ///
693 /// Note that the arguments are not passed through a shell, but given
694 /// literally to the program. This means that shell syntax like quotes,
695 /// escaped characters, word splitting, glob patterns, substitution, etc.
696 /// have no effect.
697 ///
698 /// <div class="warning">
699 ///
700 /// On Windows use caution with untrusted inputs. Most applications use the
701 /// standard convention for decoding arguments passed to them. These are safe to use with `args`.
702 /// However some applications, such as `cmd.exe` and `.bat` files, use a non-standard way of decoding arguments
703 /// and are therefore vulnerable to malicious input.
704 /// In the case of `cmd.exe` this is especially important because a malicious argument can potentially run arbitrary shell commands.
705 ///
706 /// See [Windows argument splitting][windows-args] for more details
707 /// or [`raw_arg`] for manually implementing non-standard argument encoding.
708 ///
709 /// [`raw_arg`]: crate::os::windows::process::CommandExt::raw_arg
710 /// [windows-args]: crate::process#windows-argument-splitting
711 ///
712 /// </div>
713 ///
714 /// # Examples
715 ///
716 /// Basic usage:
717 ///
718 /// ```no_run
719 /// use std::process::Command;
720 ///
721 /// Command::new("ls")
722 /// .args(["-l", "-a"])
723 /// .spawn()
724 /// .expect("ls command failed to start");
725 /// ```
726 #[stable(feature = "process", since = "1.0.0")]
args<I, S>(&mut self, args: I) -> &mut Command where I: IntoIterator<Item = S>, S: AsRef<OsStr>,727 pub fn args<I, S>(&mut self, args: I) -> &mut Command
728 where
729 I: IntoIterator<Item = S>,
730 S: AsRef<OsStr>,
731 {
732 for arg in args {
733 self.arg(arg.as_ref());
734 }
735 self
736 }
737
738 /// Inserts or updates an explicit environment variable mapping.
739 ///
740 /// This method allows you to add an environment variable mapping to the spawned process or
741 /// overwrite a previously set value. You can use [`Command::envs`] to set multiple environment
742 /// variables simultaneously.
743 ///
744 /// Child processes will inherit environment variables from their parent process by default.
745 /// Environment variables explicitly set using [`Command::env`] take precedence over inherited
746 /// variables. You can disable environment variable inheritance entirely using
747 /// [`Command::env_clear`] or for a single key using [`Command::env_remove`].
748 ///
749 /// Note that environment variable names are case-insensitive (but
750 /// case-preserving) on Windows and case-sensitive on all other platforms.
751 ///
752 /// # Examples
753 ///
754 /// Basic usage:
755 ///
756 /// ```no_run
757 /// use std::process::Command;
758 ///
759 /// Command::new("ls")
760 /// .env("PATH", "/bin")
761 /// .spawn()
762 /// .expect("ls command failed to start");
763 /// ```
764 #[stable(feature = "process", since = "1.0.0")]
env<K, V>(&mut self, key: K, val: V) -> &mut Command where K: AsRef<OsStr>, V: AsRef<OsStr>,765 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
766 where
767 K: AsRef<OsStr>,
768 V: AsRef<OsStr>,
769 {
770 self.inner.env_mut().set(key.as_ref(), val.as_ref());
771 self
772 }
773
774 /// Inserts or updates multiple explicit environment variable mappings.
775 ///
776 /// This method allows you to add multiple environment variable mappings to the spawned process
777 /// or overwrite previously set values. You can use [`Command::env`] to set a single environment
778 /// variable.
779 ///
780 /// Child processes will inherit environment variables from their parent process by default.
781 /// Environment variables explicitly set using [`Command::envs`] take precedence over inherited
782 /// variables. You can disable environment variable inheritance entirely using
783 /// [`Command::env_clear`] or for a single key using [`Command::env_remove`].
784 ///
785 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows
786 /// and case-sensitive on all other platforms.
787 ///
788 /// # Examples
789 ///
790 /// Basic usage:
791 ///
792 /// ```no_run
793 /// use std::process::{Command, Stdio};
794 /// use std::env;
795 /// use std::collections::HashMap;
796 ///
797 /// let filtered_env : HashMap<String, String> =
798 /// env::vars().filter(|&(ref k, _)|
799 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
800 /// ).collect();
801 ///
802 /// Command::new("printenv")
803 /// .stdin(Stdio::null())
804 /// .stdout(Stdio::inherit())
805 /// .env_clear()
806 /// .envs(&filtered_env)
807 /// .spawn()
808 /// .expect("printenv failed to start");
809 /// ```
810 #[stable(feature = "command_envs", since = "1.19.0")]
envs<I, K, V>(&mut self, vars: I) -> &mut Command where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>,811 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
812 where
813 I: IntoIterator<Item = (K, V)>,
814 K: AsRef<OsStr>,
815 V: AsRef<OsStr>,
816 {
817 for (ref key, ref val) in vars {
818 self.inner.env_mut().set(key.as_ref(), val.as_ref());
819 }
820 self
821 }
822
823 /// Removes an explicitly set environment variable and prevents inheriting it from a parent
824 /// process.
825 ///
826 /// This method will remove the explicit value of an environment variable set via
827 /// [`Command::env`] or [`Command::envs`]. In addition, it will prevent the spawned child
828 /// process from inheriting that environment variable from its parent process.
829 ///
830 /// After calling [`Command::env_remove`], the value associated with its key from
831 /// [`Command::get_envs`] will be [`None`].
832 ///
833 /// To clear all explicitly set environment variables and disable all environment variable
834 /// inheritance, you can use [`Command::env_clear`].
835 ///
836 /// # Examples
837 ///
838 /// Basic usage:
839 ///
840 /// ```no_run
841 /// use std::process::Command;
842 ///
843 /// Command::new("ls")
844 /// .env_remove("PATH")
845 /// .spawn()
846 /// .expect("ls command failed to start");
847 /// ```
848 #[stable(feature = "process", since = "1.0.0")]
env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command849 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
850 self.inner.env_mut().remove(key.as_ref());
851 self
852 }
853
854 /// Clears all explicitly set environment variables and prevents inheriting any parent process
855 /// environment variables.
856 ///
857 /// This method will remove all explicitly added environment variables set via [`Command::env`]
858 /// or [`Command::envs`]. In addition, it will prevent the spawned child process from inheriting
859 /// any environment variable from its parent process.
860 ///
861 /// After calling [`Command::env_remove`], the iterator from [`Command::get_envs`] will be
862 /// empty.
863 ///
864 /// You can use [`Command::env_remove`] to clear a single mapping.
865 ///
866 /// # Examples
867 ///
868 /// Basic usage:
869 ///
870 /// ```no_run
871 /// use std::process::Command;
872 ///
873 /// Command::new("ls")
874 /// .env_clear()
875 /// .spawn()
876 /// .expect("ls command failed to start");
877 /// ```
878 #[stable(feature = "process", since = "1.0.0")]
env_clear(&mut self) -> &mut Command879 pub fn env_clear(&mut self) -> &mut Command {
880 self.inner.env_mut().clear();
881 self
882 }
883
884 /// Sets the working directory for the child process.
885 ///
886 /// # Platform-specific behavior
887 ///
888 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
889 /// whether it should be interpreted relative to the parent's working
890 /// directory or relative to `current_dir`. The behavior in this case is
891 /// platform specific and unstable, and it's recommended to use
892 /// [`canonicalize`] to get an absolute program path instead.
893 ///
894 /// # Examples
895 ///
896 /// Basic usage:
897 ///
898 /// ```no_run
899 /// use std::process::Command;
900 ///
901 /// Command::new("ls")
902 /// .current_dir("/bin")
903 /// .spawn()
904 /// .expect("ls command failed to start");
905 /// ```
906 ///
907 /// [`canonicalize`]: crate::fs::canonicalize
908 #[stable(feature = "process", since = "1.0.0")]
current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command909 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
910 self.inner.cwd(dir.as_ref().as_ref());
911 self
912 }
913
914 /// Configuration for the child process's standard input (stdin) handle.
915 ///
916 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
917 /// defaults to [`piped`] when used with [`output`].
918 ///
919 /// [`inherit`]: Stdio::inherit
920 /// [`piped`]: Stdio::piped
921 /// [`spawn`]: Self::spawn
922 /// [`status`]: Self::status
923 /// [`output`]: Self::output
924 ///
925 /// # Examples
926 ///
927 /// Basic usage:
928 ///
929 /// ```no_run
930 /// use std::process::{Command, Stdio};
931 ///
932 /// Command::new("ls")
933 /// .stdin(Stdio::null())
934 /// .spawn()
935 /// .expect("ls command failed to start");
936 /// ```
937 #[stable(feature = "process", since = "1.0.0")]
stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command938 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
939 self.inner.stdin(cfg.into().0);
940 self
941 }
942
943 /// Configuration for the child process's standard output (stdout) handle.
944 ///
945 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
946 /// defaults to [`piped`] when used with [`output`].
947 ///
948 /// [`inherit`]: Stdio::inherit
949 /// [`piped`]: Stdio::piped
950 /// [`spawn`]: Self::spawn
951 /// [`status`]: Self::status
952 /// [`output`]: Self::output
953 ///
954 /// # Examples
955 ///
956 /// Basic usage:
957 ///
958 /// ```no_run
959 /// use std::process::{Command, Stdio};
960 ///
961 /// Command::new("ls")
962 /// .stdout(Stdio::null())
963 /// .spawn()
964 /// .expect("ls command failed to start");
965 /// ```
966 #[stable(feature = "process", since = "1.0.0")]
stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command967 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
968 self.inner.stdout(cfg.into().0);
969 self
970 }
971
972 /// Configuration for the child process's standard error (stderr) handle.
973 ///
974 /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and
975 /// defaults to [`piped`] when used with [`output`].
976 ///
977 /// [`inherit`]: Stdio::inherit
978 /// [`piped`]: Stdio::piped
979 /// [`spawn`]: Self::spawn
980 /// [`status`]: Self::status
981 /// [`output`]: Self::output
982 ///
983 /// # Examples
984 ///
985 /// Basic usage:
986 ///
987 /// ```no_run
988 /// use std::process::{Command, Stdio};
989 ///
990 /// Command::new("ls")
991 /// .stderr(Stdio::null())
992 /// .spawn()
993 /// .expect("ls command failed to start");
994 /// ```
995 #[stable(feature = "process", since = "1.0.0")]
stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command996 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
997 self.inner.stderr(cfg.into().0);
998 self
999 }
1000
1001 /// Executes the command as a child process, returning a handle to it.
1002 ///
1003 /// By default, stdin, stdout and stderr are inherited from the parent.
1004 ///
1005 /// # Examples
1006 ///
1007 /// Basic usage:
1008 ///
1009 /// ```no_run
1010 /// use std::process::Command;
1011 ///
1012 /// Command::new("ls")
1013 /// .spawn()
1014 /// .expect("ls command failed to start");
1015 /// ```
1016 #[stable(feature = "process", since = "1.0.0")]
spawn(&mut self) -> io::Result<Child>1017 pub fn spawn(&mut self) -> io::Result<Child> {
1018 self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
1019 }
1020
1021 /// Executes the command as a child process, waiting for it to finish and
1022 /// collecting all of its output.
1023 ///
1024 /// By default, stdout and stderr are captured (and used to provide the
1025 /// resulting output). Stdin is not inherited from the parent and any
1026 /// attempt by the child process to read from the stdin stream will result
1027 /// in the stream immediately closing.
1028 ///
1029 /// # Examples
1030 ///
1031 /// ```should_panic
1032 /// use std::process::Command;
1033 /// use std::io::{self, Write};
1034 /// let output = Command::new("/bin/cat")
1035 /// .arg("file.txt")
1036 /// .output()
1037 /// .expect("failed to execute process");
1038 ///
1039 /// println!("status: {}", output.status);
1040 /// io::stdout().write_all(&output.stdout).unwrap();
1041 /// io::stderr().write_all(&output.stderr).unwrap();
1042 ///
1043 /// assert!(output.status.success());
1044 /// ```
1045 #[stable(feature = "process", since = "1.0.0")]
output(&mut self) -> io::Result<Output>1046 pub fn output(&mut self) -> io::Result<Output> {
1047 let (status, stdout, stderr) = self.inner.output()?;
1048 Ok(Output { status: ExitStatus(status), stdout, stderr })
1049 }
1050
1051 /// Executes a command as a child process, waiting for it to finish and
1052 /// collecting its status.
1053 ///
1054 /// By default, stdin, stdout and stderr are inherited from the parent.
1055 ///
1056 /// # Examples
1057 ///
1058 /// ```should_panic
1059 /// use std::process::Command;
1060 ///
1061 /// let status = Command::new("/bin/cat")
1062 /// .arg("file.txt")
1063 /// .status()
1064 /// .expect("failed to execute process");
1065 ///
1066 /// println!("process finished with: {status}");
1067 ///
1068 /// assert!(status.success());
1069 /// ```
1070 #[stable(feature = "process", since = "1.0.0")]
status(&mut self) -> io::Result<ExitStatus>1071 pub fn status(&mut self) -> io::Result<ExitStatus> {
1072 self.inner
1073 .spawn(imp::Stdio::Inherit, true)
1074 .map(Child::from_inner)
1075 .and_then(|mut p| p.wait())
1076 }
1077
1078 /// Returns the path to the program that was given to [`Command::new`].
1079 ///
1080 /// # Examples
1081 ///
1082 /// ```
1083 /// use std::process::Command;
1084 ///
1085 /// let cmd = Command::new("echo");
1086 /// assert_eq!(cmd.get_program(), "echo");
1087 /// ```
1088 #[must_use]
1089 #[stable(feature = "command_access", since = "1.57.0")]
get_program(&self) -> &OsStr1090 pub fn get_program(&self) -> &OsStr {
1091 self.inner.get_program()
1092 }
1093
1094 /// Returns an iterator of the arguments that will be passed to the program.
1095 ///
1096 /// This does not include the path to the program as the first argument;
1097 /// it only includes the arguments specified with [`Command::arg`] and
1098 /// [`Command::args`].
1099 ///
1100 /// # Examples
1101 ///
1102 /// ```
1103 /// use std::ffi::OsStr;
1104 /// use std::process::Command;
1105 ///
1106 /// let mut cmd = Command::new("echo");
1107 /// cmd.arg("first").arg("second");
1108 /// let args: Vec<&OsStr> = cmd.get_args().collect();
1109 /// assert_eq!(args, &["first", "second"]);
1110 /// ```
1111 #[stable(feature = "command_access", since = "1.57.0")]
get_args(&self) -> CommandArgs<'_>1112 pub fn get_args(&self) -> CommandArgs<'_> {
1113 CommandArgs { inner: self.inner.get_args() }
1114 }
1115
1116 /// Returns an iterator of the environment variables explicitly set for the child process.
1117 ///
1118 /// Environment variables explicitly set using [`Command::env`], [`Command::envs`], and
1119 /// [`Command::env_remove`] can be retrieved with this method.
1120 ///
1121 /// Note that this output does not include environment variables inherited from the parent
1122 /// process.
1123 ///
1124 /// Each element is a tuple key/value pair `(&OsStr, Option<&OsStr>)`. A [`None`] value
1125 /// indicates its key was explicitly removed via [`Command::env_remove`]. The associated key for
1126 /// the [`None`] value will no longer inherit from its parent process.
1127 ///
1128 /// An empty iterator can indicate that no explicit mappings were added or that
1129 /// [`Command::env_clear`] was called. After calling [`Command::env_clear`], the child process
1130 /// will not inherit any environment variables from its parent process.
1131 ///
1132 /// # Examples
1133 ///
1134 /// ```
1135 /// use std::ffi::OsStr;
1136 /// use std::process::Command;
1137 ///
1138 /// let mut cmd = Command::new("ls");
1139 /// cmd.env("TERM", "dumb").env_remove("TZ");
1140 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
1141 /// assert_eq!(envs, &[
1142 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
1143 /// (OsStr::new("TZ"), None)
1144 /// ]);
1145 /// ```
1146 #[stable(feature = "command_access", since = "1.57.0")]
get_envs(&self) -> CommandEnvs<'_>1147 pub fn get_envs(&self) -> CommandEnvs<'_> {
1148 self.inner.get_envs()
1149 }
1150
1151 /// Returns the working directory for the child process.
1152 ///
1153 /// This returns [`None`] if the working directory will not be changed.
1154 ///
1155 /// # Examples
1156 ///
1157 /// ```
1158 /// use std::path::Path;
1159 /// use std::process::Command;
1160 ///
1161 /// let mut cmd = Command::new("ls");
1162 /// assert_eq!(cmd.get_current_dir(), None);
1163 /// cmd.current_dir("/bin");
1164 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
1165 /// ```
1166 #[must_use]
1167 #[stable(feature = "command_access", since = "1.57.0")]
get_current_dir(&self) -> Option<&Path>1168 pub fn get_current_dir(&self) -> Option<&Path> {
1169 self.inner.get_current_dir()
1170 }
1171 }
1172
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 impl fmt::Debug for Command {
1175 /// Format the program and arguments of a Command for display. Any
1176 /// non-utf8 data is lossily converted using the utf8 replacement
1177 /// character.
1178 ///
1179 /// The default format approximates a shell invocation of the program along with its
1180 /// arguments. It does not include most of the other command properties. The output is not guaranteed to work
1181 /// (e.g. due to lack of shell-escaping or differences in path resolution)
1182 /// On some platforms you can use [the alternate syntax] to show more fields.
1183 ///
1184 /// Note that the debug implementation is platform-specific.
1185 ///
1186 /// [the alternate syntax]: fmt#sign0
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188 self.inner.fmt(f)
1189 }
1190 }
1191
1192 impl AsInner<imp::Command> for Command {
1193 #[inline]
as_inner(&self) -> &imp::Command1194 fn as_inner(&self) -> &imp::Command {
1195 &self.inner
1196 }
1197 }
1198
1199 impl AsInnerMut<imp::Command> for Command {
1200 #[inline]
as_inner_mut(&mut self) -> &mut imp::Command1201 fn as_inner_mut(&mut self) -> &mut imp::Command {
1202 &mut self.inner
1203 }
1204 }
1205
1206 /// An iterator over the command arguments.
1207 ///
1208 /// This struct is created by [`Command::get_args`]. See its documentation for
1209 /// more.
1210 #[must_use = "iterators are lazy and do nothing unless consumed"]
1211 #[stable(feature = "command_access", since = "1.57.0")]
1212 #[derive(Debug)]
1213 pub struct CommandArgs<'a> {
1214 inner: imp::CommandArgs<'a>,
1215 }
1216
1217 #[stable(feature = "command_access", since = "1.57.0")]
1218 impl<'a> Iterator for CommandArgs<'a> {
1219 type Item = &'a OsStr;
next(&mut self) -> Option<&'a OsStr>1220 fn next(&mut self) -> Option<&'a OsStr> {
1221 self.inner.next()
1222 }
size_hint(&self) -> (usize, Option<usize>)1223 fn size_hint(&self) -> (usize, Option<usize>) {
1224 self.inner.size_hint()
1225 }
1226 }
1227
1228 #[stable(feature = "command_access", since = "1.57.0")]
1229 impl<'a> ExactSizeIterator for CommandArgs<'a> {
len(&self) -> usize1230 fn len(&self) -> usize {
1231 self.inner.len()
1232 }
is_empty(&self) -> bool1233 fn is_empty(&self) -> bool {
1234 self.inner.is_empty()
1235 }
1236 }
1237
1238 /// The output of a finished process.
1239 ///
1240 /// This is returned in a Result by either the [`output`] method of a
1241 /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
1242 /// process.
1243 ///
1244 /// [`output`]: Command::output
1245 /// [`wait_with_output`]: Child::wait_with_output
1246 #[derive(PartialEq, Eq, Clone)]
1247 #[stable(feature = "process", since = "1.0.0")]
1248 pub struct Output {
1249 /// The status (exit code) of the process.
1250 #[stable(feature = "process", since = "1.0.0")]
1251 pub status: ExitStatus,
1252 /// The data that the process wrote to stdout.
1253 #[stable(feature = "process", since = "1.0.0")]
1254 pub stdout: Vec<u8>,
1255 /// The data that the process wrote to stderr.
1256 #[stable(feature = "process", since = "1.0.0")]
1257 pub stderr: Vec<u8>,
1258 }
1259
1260 // If either stderr or stdout are valid utf8 strings it prints the valid
1261 // strings, otherwise it prints the byte sequence instead
1262 #[stable(feature = "process_output_debug", since = "1.7.0")]
1263 impl fmt::Debug for Output {
fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result1264 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1265 let stdout_utf8 = str::from_utf8(&self.stdout);
1266 let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
1267 Ok(ref str) => str,
1268 Err(_) => &self.stdout,
1269 };
1270
1271 let stderr_utf8 = str::from_utf8(&self.stderr);
1272 let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
1273 Ok(ref str) => str,
1274 Err(_) => &self.stderr,
1275 };
1276
1277 fmt.debug_struct("Output")
1278 .field("status", &self.status)
1279 .field("stdout", stdout_debug)
1280 .field("stderr", stderr_debug)
1281 .finish()
1282 }
1283 }
1284
1285 /// Describes what to do with a standard I/O stream for a child process when
1286 /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
1287 ///
1288 /// [`stdin`]: Command::stdin
1289 /// [`stdout`]: Command::stdout
1290 /// [`stderr`]: Command::stderr
1291 #[stable(feature = "process", since = "1.0.0")]
1292 pub struct Stdio(imp::Stdio);
1293
1294 impl Stdio {
1295 /// A new pipe should be arranged to connect the parent and child processes.
1296 ///
1297 /// # Examples
1298 ///
1299 /// With stdout:
1300 ///
1301 /// ```no_run
1302 /// use std::process::{Command, Stdio};
1303 ///
1304 /// let output = Command::new("echo")
1305 /// .arg("Hello, world!")
1306 /// .stdout(Stdio::piped())
1307 /// .output()
1308 /// .expect("Failed to execute command");
1309 ///
1310 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
1311 /// // Nothing echoed to console
1312 /// ```
1313 ///
1314 /// With stdin:
1315 ///
1316 /// ```no_run
1317 /// use std::io::Write;
1318 /// use std::process::{Command, Stdio};
1319 ///
1320 /// let mut child = Command::new("rev")
1321 /// .stdin(Stdio::piped())
1322 /// .stdout(Stdio::piped())
1323 /// .spawn()
1324 /// .expect("Failed to spawn child process");
1325 ///
1326 /// let mut stdin = child.stdin.take().expect("Failed to open stdin");
1327 /// std::thread::spawn(move || {
1328 /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
1329 /// });
1330 ///
1331 /// let output = child.wait_with_output().expect("Failed to read stdout");
1332 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
1333 /// ```
1334 ///
1335 /// Writing more than a pipe buffer's worth of input to stdin without also reading
1336 /// stdout and stderr at the same time may cause a deadlock.
1337 /// This is an issue when running any program that doesn't guarantee that it reads
1338 /// its entire stdin before writing more than a pipe buffer's worth of output.
1339 /// The size of a pipe buffer varies on different targets.
1340 ///
1341 #[must_use]
1342 #[stable(feature = "process", since = "1.0.0")]
piped() -> Stdio1343 pub fn piped() -> Stdio {
1344 Stdio(imp::Stdio::MakePipe)
1345 }
1346
1347 /// The child inherits from the corresponding parent descriptor.
1348 ///
1349 /// # Examples
1350 ///
1351 /// With stdout:
1352 ///
1353 /// ```no_run
1354 /// use std::process::{Command, Stdio};
1355 ///
1356 /// let output = Command::new("echo")
1357 /// .arg("Hello, world!")
1358 /// .stdout(Stdio::inherit())
1359 /// .output()
1360 /// .expect("Failed to execute command");
1361 ///
1362 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1363 /// // "Hello, world!" echoed to console
1364 /// ```
1365 ///
1366 /// With stdin:
1367 ///
1368 /// ```no_run
1369 /// use std::process::{Command, Stdio};
1370 /// use std::io::{self, Write};
1371 ///
1372 /// let output = Command::new("rev")
1373 /// .stdin(Stdio::inherit())
1374 /// .stdout(Stdio::piped())
1375 /// .output()
1376 /// .expect("Failed to execute command");
1377 ///
1378 /// print!("You piped in the reverse of: ");
1379 /// io::stdout().write_all(&output.stdout).unwrap();
1380 /// ```
1381 #[must_use]
1382 #[stable(feature = "process", since = "1.0.0")]
inherit() -> Stdio1383 pub fn inherit() -> Stdio {
1384 Stdio(imp::Stdio::Inherit)
1385 }
1386
1387 /// This stream will be ignored. This is the equivalent of attaching the
1388 /// stream to `/dev/null`.
1389 ///
1390 /// # Examples
1391 ///
1392 /// With stdout:
1393 ///
1394 /// ```no_run
1395 /// use std::process::{Command, Stdio};
1396 ///
1397 /// let output = Command::new("echo")
1398 /// .arg("Hello, world!")
1399 /// .stdout(Stdio::null())
1400 /// .output()
1401 /// .expect("Failed to execute command");
1402 ///
1403 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1404 /// // Nothing echoed to console
1405 /// ```
1406 ///
1407 /// With stdin:
1408 ///
1409 /// ```no_run
1410 /// use std::process::{Command, Stdio};
1411 ///
1412 /// let output = Command::new("rev")
1413 /// .stdin(Stdio::null())
1414 /// .stdout(Stdio::piped())
1415 /// .output()
1416 /// .expect("Failed to execute command");
1417 ///
1418 /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
1419 /// // Ignores any piped-in input
1420 /// ```
1421 #[must_use]
1422 #[stable(feature = "process", since = "1.0.0")]
null() -> Stdio1423 pub fn null() -> Stdio {
1424 Stdio(imp::Stdio::Null)
1425 }
1426
1427 /// Returns `true` if this requires [`Command`] to create a new pipe.
1428 ///
1429 /// # Example
1430 ///
1431 /// ```
1432 /// #![feature(stdio_makes_pipe)]
1433 /// use std::process::Stdio;
1434 ///
1435 /// let io = Stdio::piped();
1436 /// assert_eq!(io.makes_pipe(), true);
1437 /// ```
1438 #[unstable(feature = "stdio_makes_pipe", issue = "98288")]
makes_pipe(&self) -> bool1439 pub fn makes_pipe(&self) -> bool {
1440 matches!(self.0, imp::Stdio::MakePipe)
1441 }
1442 }
1443
1444 impl FromInner<imp::Stdio> for Stdio {
from_inner(inner: imp::Stdio) -> Stdio1445 fn from_inner(inner: imp::Stdio) -> Stdio {
1446 Stdio(inner)
1447 }
1448 }
1449
1450 #[stable(feature = "std_debug", since = "1.16.0")]
1451 impl fmt::Debug for Stdio {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453 f.debug_struct("Stdio").finish_non_exhaustive()
1454 }
1455 }
1456
1457 #[stable(feature = "stdio_from", since = "1.20.0")]
1458 impl From<ChildStdin> for Stdio {
1459 /// Converts a [`ChildStdin`] into a [`Stdio`].
1460 ///
1461 /// # Examples
1462 ///
1463 /// `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood.
1464 ///
1465 /// ```rust,no_run
1466 /// use std::process::{Command, Stdio};
1467 ///
1468 /// let reverse = Command::new("rev")
1469 /// .stdin(Stdio::piped())
1470 /// .spawn()
1471 /// .expect("failed reverse command");
1472 ///
1473 /// let _echo = Command::new("echo")
1474 /// .arg("Hello, world!")
1475 /// .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
1476 /// .output()
1477 /// .expect("failed echo command");
1478 ///
1479 /// // "!dlrow ,olleH" echoed to console
1480 /// ```
from(child: ChildStdin) -> Stdio1481 fn from(child: ChildStdin) -> Stdio {
1482 Stdio::from_inner(child.into_inner().into())
1483 }
1484 }
1485
1486 #[stable(feature = "stdio_from", since = "1.20.0")]
1487 impl From<ChildStdout> for Stdio {
1488 /// Converts a [`ChildStdout`] into a [`Stdio`].
1489 ///
1490 /// # Examples
1491 ///
1492 /// `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood.
1493 ///
1494 /// ```rust,no_run
1495 /// use std::process::{Command, Stdio};
1496 ///
1497 /// let hello = Command::new("echo")
1498 /// .arg("Hello, world!")
1499 /// .stdout(Stdio::piped())
1500 /// .spawn()
1501 /// .expect("failed echo command");
1502 ///
1503 /// let reverse = Command::new("rev")
1504 /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here
1505 /// .output()
1506 /// .expect("failed reverse command");
1507 ///
1508 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
1509 /// ```
from(child: ChildStdout) -> Stdio1510 fn from(child: ChildStdout) -> Stdio {
1511 Stdio::from_inner(child.into_inner().into())
1512 }
1513 }
1514
1515 #[stable(feature = "stdio_from", since = "1.20.0")]
1516 impl From<ChildStderr> for Stdio {
1517 /// Converts a [`ChildStderr`] into a [`Stdio`].
1518 ///
1519 /// # Examples
1520 ///
1521 /// ```rust,no_run
1522 /// use std::process::{Command, Stdio};
1523 ///
1524 /// let reverse = Command::new("rev")
1525 /// .arg("non_existing_file.txt")
1526 /// .stderr(Stdio::piped())
1527 /// .spawn()
1528 /// .expect("failed reverse command");
1529 ///
1530 /// let cat = Command::new("cat")
1531 /// .arg("-")
1532 /// .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
1533 /// .output()
1534 /// .expect("failed echo command");
1535 ///
1536 /// assert_eq!(
1537 /// String::from_utf8_lossy(&cat.stdout),
1538 /// "rev: cannot open non_existing_file.txt: No such file or directory\n"
1539 /// );
1540 /// ```
from(child: ChildStderr) -> Stdio1541 fn from(child: ChildStderr) -> Stdio {
1542 Stdio::from_inner(child.into_inner().into())
1543 }
1544 }
1545
1546 #[stable(feature = "stdio_from", since = "1.20.0")]
1547 impl From<fs::File> for Stdio {
1548 /// Converts a [`File`](fs::File) into a [`Stdio`].
1549 ///
1550 /// # Examples
1551 ///
1552 /// `File` will be converted to `Stdio` using `Stdio::from` under the hood.
1553 ///
1554 /// ```rust,no_run
1555 /// use std::fs::File;
1556 /// use std::process::Command;
1557 ///
1558 /// // With the `foo.txt` file containing "Hello, world!"
1559 /// let file = File::open("foo.txt").unwrap();
1560 ///
1561 /// let reverse = Command::new("rev")
1562 /// .stdin(file) // Implicit File conversion into a Stdio
1563 /// .output()
1564 /// .expect("failed reverse command");
1565 ///
1566 /// assert_eq!(reverse.stdout, b"!dlrow ,olleH");
1567 /// ```
from(file: fs::File) -> Stdio1568 fn from(file: fs::File) -> Stdio {
1569 Stdio::from_inner(file.into_inner().into())
1570 }
1571 }
1572
1573 /// Describes the result of a process after it has terminated.
1574 ///
1575 /// This `struct` is used to represent the exit status or other termination of a child process.
1576 /// Child processes are created via the [`Command`] struct and their exit
1577 /// status is exposed through the [`status`] method, or the [`wait`] method
1578 /// of a [`Child`] process.
1579 ///
1580 /// An `ExitStatus` represents every possible disposition of a process. On Unix this
1581 /// is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`).
1582 ///
1583 /// For proper error reporting of failed processes, print the value of `ExitStatus` or
1584 /// `ExitStatusError` using their implementations of [`Display`](crate::fmt::Display).
1585 ///
1586 /// # Differences from `ExitCode`
1587 ///
1588 /// [`ExitCode`] is intended for terminating the currently running process, via
1589 /// the `Termination` trait, in contrast to `ExitStatus`, which represents the
1590 /// termination of a child process. These APIs are separate due to platform
1591 /// compatibility differences and their expected usage; it is not generally
1592 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1593 /// process after the fact.
1594 ///
1595 /// [`status`]: Command::status
1596 /// [`wait`]: Child::wait
1597 //
1598 // We speak slightly loosely (here and in various other places in the stdlib docs) about `exit`
1599 // vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a
1600 // matter of convention and tradition. For clarity we usually speak of `exit`, even when we might
1601 // mean an underlying system call such as `_exit`.
1602 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1603 #[stable(feature = "process", since = "1.0.0")]
1604 pub struct ExitStatus(imp::ExitStatus);
1605
1606 /// Allows extension traits within `std`.
1607 #[unstable(feature = "sealed", issue = "none")]
1608 impl crate::sealed::Sealed for ExitStatus {}
1609
1610 impl ExitStatus {
1611 /// Was termination successful? Returns a `Result`.
1612 ///
1613 /// # Examples
1614 ///
1615 /// ```
1616 /// #![feature(exit_status_error)]
1617 /// # if cfg!(unix) {
1618 /// use std::process::Command;
1619 ///
1620 /// let status = Command::new("ls")
1621 /// .arg("/dev/nonexistent")
1622 /// .status()
1623 /// .expect("ls could not be executed");
1624 ///
1625 /// println!("ls: {status}");
1626 /// status.exit_ok().expect_err("/dev/nonexistent could be listed!");
1627 /// # } // cfg!(unix)
1628 /// ```
1629 #[unstable(feature = "exit_status_error", issue = "84908")]
exit_ok(&self) -> Result<(), ExitStatusError>1630 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1631 self.0.exit_ok().map_err(ExitStatusError)
1632 }
1633
1634 /// Was termination successful? Signal termination is not considered a
1635 /// success, and success is defined as a zero exit status.
1636 ///
1637 /// # Examples
1638 ///
1639 /// ```rust,no_run
1640 /// use std::process::Command;
1641 ///
1642 /// let status = Command::new("mkdir")
1643 /// .arg("projects")
1644 /// .status()
1645 /// .expect("failed to execute mkdir");
1646 ///
1647 /// if status.success() {
1648 /// println!("'projects/' directory created");
1649 /// } else {
1650 /// println!("failed to create 'projects/' directory: {status}");
1651 /// }
1652 /// ```
1653 #[must_use]
1654 #[stable(feature = "process", since = "1.0.0")]
success(&self) -> bool1655 pub fn success(&self) -> bool {
1656 self.0.exit_ok().is_ok()
1657 }
1658
1659 /// Returns the exit code of the process, if any.
1660 ///
1661 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1662 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1663 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1664 /// runtime system (often, for example, 255, 254, 127 or 126).
1665 ///
1666 /// On Unix, this will return `None` if the process was terminated by a signal.
1667 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
1668 /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
1669 ///
1670 /// # Examples
1671 ///
1672 /// ```no_run
1673 /// use std::process::Command;
1674 ///
1675 /// let status = Command::new("mkdir")
1676 /// .arg("projects")
1677 /// .status()
1678 /// .expect("failed to execute mkdir");
1679 ///
1680 /// match status.code() {
1681 /// Some(code) => println!("Exited with status code: {code}"),
1682 /// None => println!("Process terminated by signal")
1683 /// }
1684 /// ```
1685 #[must_use]
1686 #[stable(feature = "process", since = "1.0.0")]
code(&self) -> Option<i32>1687 pub fn code(&self) -> Option<i32> {
1688 self.0.code()
1689 }
1690 }
1691
1692 impl AsInner<imp::ExitStatus> for ExitStatus {
1693 #[inline]
as_inner(&self) -> &imp::ExitStatus1694 fn as_inner(&self) -> &imp::ExitStatus {
1695 &self.0
1696 }
1697 }
1698
1699 impl FromInner<imp::ExitStatus> for ExitStatus {
from_inner(s: imp::ExitStatus) -> ExitStatus1700 fn from_inner(s: imp::ExitStatus) -> ExitStatus {
1701 ExitStatus(s)
1702 }
1703 }
1704
1705 #[stable(feature = "process", since = "1.0.0")]
1706 impl fmt::Display for ExitStatus {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1707 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1708 self.0.fmt(f)
1709 }
1710 }
1711
1712 /// Allows extension traits within `std`.
1713 #[unstable(feature = "sealed", issue = "none")]
1714 impl crate::sealed::Sealed for ExitStatusError {}
1715
1716 /// Describes the result of a process after it has failed
1717 ///
1718 /// Produced by the [`.exit_ok`](ExitStatus::exit_ok) method on [`ExitStatus`].
1719 ///
1720 /// # Examples
1721 ///
1722 /// ```
1723 /// #![feature(exit_status_error)]
1724 /// # if cfg!(unix) {
1725 /// use std::process::{Command, ExitStatusError};
1726 ///
1727 /// fn run(cmd: &str) -> Result<(),ExitStatusError> {
1728 /// Command::new(cmd).status().unwrap().exit_ok()?;
1729 /// Ok(())
1730 /// }
1731 ///
1732 /// run("true").unwrap();
1733 /// run("false").unwrap_err();
1734 /// # } // cfg!(unix)
1735 /// ```
1736 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
1737 #[unstable(feature = "exit_status_error", issue = "84908")]
1738 // The definition of imp::ExitStatusError should ideally be such that
1739 // Result<(), imp::ExitStatusError> has an identical representation to imp::ExitStatus.
1740 pub struct ExitStatusError(imp::ExitStatusError);
1741
1742 #[unstable(feature = "exit_status_error", issue = "84908")]
1743 impl ExitStatusError {
1744 /// Reports the exit code, if applicable, from an `ExitStatusError`.
1745 ///
1746 /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
1747 /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8
1748 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
1749 /// runtime system (often, for example, 255, 254, 127 or 126).
1750 ///
1751 /// On Unix, this will return `None` if the process was terminated by a signal. If you want to
1752 /// handle such situations specially, consider using methods from
1753 /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt).
1754 ///
1755 /// If the process finished by calling `exit` with a nonzero value, this will return
1756 /// that exit status.
1757 ///
1758 /// If the error was something else, it will return `None`.
1759 ///
1760 /// If the process exited successfully (ie, by calling `exit(0)`), there is no
1761 /// `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero.
1762 ///
1763 /// # Examples
1764 ///
1765 /// ```
1766 /// #![feature(exit_status_error)]
1767 /// # #[cfg(unix)] {
1768 /// use std::process::Command;
1769 ///
1770 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1771 /// assert_eq!(bad.code(), Some(1));
1772 /// # } // #[cfg(unix)]
1773 /// ```
1774 #[must_use]
code(&self) -> Option<i32>1775 pub fn code(&self) -> Option<i32> {
1776 self.code_nonzero().map(Into::into)
1777 }
1778
1779 /// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1780 ///
1781 /// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1782 ///
1783 /// Plain `code`, returning a plain integer, is provided because it is often more convenient.
1784 /// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
1785 /// a type-level guarantee of nonzeroness.
1786 ///
1787 /// # Examples
1788 ///
1789 /// ```
1790 /// #![feature(exit_status_error)]
1791 /// # if cfg!(unix) {
1792 /// use std::num::NonZeroI32;
1793 /// use std::process::Command;
1794 ///
1795 /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1796 /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1797 /// # } // cfg!(unix)
1798 /// ```
1799 #[must_use]
code_nonzero(&self) -> Option<NonZeroI32>1800 pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1801 self.0.code()
1802 }
1803
1804 /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
1805 #[must_use]
into_status(&self) -> ExitStatus1806 pub fn into_status(&self) -> ExitStatus {
1807 ExitStatus(self.0.into())
1808 }
1809 }
1810
1811 #[unstable(feature = "exit_status_error", issue = "84908")]
1812 impl Into<ExitStatus> for ExitStatusError {
into(self) -> ExitStatus1813 fn into(self) -> ExitStatus {
1814 ExitStatus(self.0.into())
1815 }
1816 }
1817
1818 #[unstable(feature = "exit_status_error", issue = "84908")]
1819 impl fmt::Display for ExitStatusError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1820 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1821 write!(f, "process exited unsuccessfully: {}", self.into_status())
1822 }
1823 }
1824
1825 #[unstable(feature = "exit_status_error", issue = "84908")]
1826 impl crate::error::Error for ExitStatusError {}
1827
1828 /// This type represents the status code the current process can return
1829 /// to its parent under normal termination.
1830 ///
1831 /// `ExitCode` is intended to be consumed only by the standard library (via
1832 /// [`Termination::report()`]), and intentionally does not provide accessors like
1833 /// `PartialEq`, `Eq`, or `Hash`. Instead the standard library provides the
1834 /// canonical `SUCCESS` and `FAILURE` exit codes as well as `From<u8> for
1835 /// ExitCode` for constructing other arbitrary exit codes.
1836 ///
1837 /// # Portability
1838 ///
1839 /// Numeric values used in this type don't have portable meanings, and
1840 /// different platforms may mask different amounts of them.
1841 ///
1842 /// For the platform's canonical successful and unsuccessful codes, see
1843 /// the [`SUCCESS`] and [`FAILURE`] associated items.
1844 ///
1845 /// [`SUCCESS`]: ExitCode::SUCCESS
1846 /// [`FAILURE`]: ExitCode::FAILURE
1847 ///
1848 /// # Differences from `ExitStatus`
1849 ///
1850 /// `ExitCode` is intended for terminating the currently running process, via
1851 /// the `Termination` trait, in contrast to [`ExitStatus`], which represents the
1852 /// termination of a child process. These APIs are separate due to platform
1853 /// compatibility differences and their expected usage; it is not generally
1854 /// possible to exactly reproduce an `ExitStatus` from a child for the current
1855 /// process after the fact.
1856 ///
1857 /// # Examples
1858 ///
1859 /// `ExitCode` can be returned from the `main` function of a crate, as it implements
1860 /// [`Termination`]:
1861 ///
1862 /// ```
1863 /// use std::process::ExitCode;
1864 /// # fn check_foo() -> bool { true }
1865 ///
1866 /// fn main() -> ExitCode {
1867 /// if !check_foo() {
1868 /// return ExitCode::from(42);
1869 /// }
1870 ///
1871 /// ExitCode::SUCCESS
1872 /// }
1873 /// ```
1874 #[derive(Clone, Copy, Debug)]
1875 #[stable(feature = "process_exitcode", since = "1.61.0")]
1876 pub struct ExitCode(imp::ExitCode);
1877
1878 /// Allows extension traits within `std`.
1879 #[unstable(feature = "sealed", issue = "none")]
1880 impl crate::sealed::Sealed for ExitCode {}
1881
1882 #[stable(feature = "process_exitcode", since = "1.61.0")]
1883 impl ExitCode {
1884 /// The canonical `ExitCode` for successful termination on this platform.
1885 ///
1886 /// Note that a `()`-returning `main` implicitly results in a successful
1887 /// termination, so there's no need to return this from `main` unless
1888 /// you're also returning other possible codes.
1889 #[stable(feature = "process_exitcode", since = "1.61.0")]
1890 pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
1891
1892 /// The canonical `ExitCode` for unsuccessful termination on this platform.
1893 ///
1894 /// If you're only returning this and `SUCCESS` from `main`, consider
1895 /// instead returning `Err(_)` and `Ok(())` respectively, which will
1896 /// return the same codes (but will also `eprintln!` the error).
1897 #[stable(feature = "process_exitcode", since = "1.61.0")]
1898 pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
1899
1900 /// Exit the current process with the given `ExitCode`.
1901 ///
1902 /// Note that this has the same caveats as [`process::exit()`][exit], namely that this function
1903 /// terminates the process immediately, so no destructors on the current stack or any other
1904 /// thread's stack will be run. If a clean shutdown is needed, it is recommended to simply
1905 /// return this ExitCode from the `main` function, as demonstrated in the [type
1906 /// documentation](#examples).
1907 ///
1908 /// # Differences from `process::exit()`
1909 ///
1910 /// `process::exit()` accepts any `i32` value as the exit code for the process; however, there
1911 /// are platforms that only use a subset of that value (see [`process::exit` platform-specific
1912 /// behavior][exit#platform-specific-behavior]). `ExitCode` exists because of this; only
1913 /// `ExitCode`s that are supported by a majority of our platforms can be created, so those
1914 /// problems don't exist (as much) with this method.
1915 ///
1916 /// # Examples
1917 ///
1918 /// ```
1919 /// #![feature(exitcode_exit_method)]
1920 /// # use std::process::ExitCode;
1921 /// # use std::fmt;
1922 /// # enum UhOhError { GenericProblem, Specific, WithCode { exit_code: ExitCode, _x: () } }
1923 /// # impl fmt::Display for UhOhError {
1924 /// # fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { unimplemented!() }
1925 /// # }
1926 /// // there's no way to gracefully recover from an UhOhError, so we just
1927 /// // print a message and exit
1928 /// fn handle_unrecoverable_error(err: UhOhError) -> ! {
1929 /// eprintln!("UH OH! {err}");
1930 /// let code = match err {
1931 /// UhOhError::GenericProblem => ExitCode::FAILURE,
1932 /// UhOhError::Specific => ExitCode::from(3),
1933 /// UhOhError::WithCode { exit_code, .. } => exit_code,
1934 /// };
1935 /// code.exit_process()
1936 /// }
1937 /// ```
1938 #[unstable(feature = "exitcode_exit_method", issue = "97100")]
exit_process(self) -> !1939 pub fn exit_process(self) -> ! {
1940 exit(self.to_i32())
1941 }
1942 }
1943
1944 impl ExitCode {
1945 // This is private/perma-unstable because ExitCode is opaque; we don't know that i32 will serve
1946 // all usecases, for example windows seems to use u32, unix uses the 8-15th bits of an i32, we
1947 // likely want to isolate users anything that could restrict the platform specific
1948 // representation of an ExitCode
1949 //
1950 // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426
1951 /// Convert an `ExitCode` into an i32
1952 #[unstable(
1953 feature = "process_exitcode_internals",
1954 reason = "exposed only for libstd",
1955 issue = "none"
1956 )]
1957 #[inline]
1958 #[doc(hidden)]
to_i32(self) -> i321959 pub fn to_i32(self) -> i32 {
1960 self.0.as_i32()
1961 }
1962 }
1963
1964 #[stable(feature = "process_exitcode", since = "1.61.0")]
1965 impl From<u8> for ExitCode {
1966 /// Construct an `ExitCode` from an arbitrary u8 value.
from(code: u8) -> Self1967 fn from(code: u8) -> Self {
1968 ExitCode(imp::ExitCode::from(code))
1969 }
1970 }
1971
1972 impl AsInner<imp::ExitCode> for ExitCode {
1973 #[inline]
as_inner(&self) -> &imp::ExitCode1974 fn as_inner(&self) -> &imp::ExitCode {
1975 &self.0
1976 }
1977 }
1978
1979 impl FromInner<imp::ExitCode> for ExitCode {
from_inner(s: imp::ExitCode) -> ExitCode1980 fn from_inner(s: imp::ExitCode) -> ExitCode {
1981 ExitCode(s)
1982 }
1983 }
1984
1985 impl Child {
1986 /// Forces the child process to exit. If the child has already exited, `Ok(())`
1987 /// is returned.
1988 ///
1989 /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function.
1990 ///
1991 /// This is equivalent to sending a SIGKILL on Unix platforms.
1992 ///
1993 /// # Examples
1994 ///
1995 /// Basic usage:
1996 ///
1997 /// ```no_run
1998 /// use std::process::Command;
1999 ///
2000 /// let mut command = Command::new("yes");
2001 /// if let Ok(mut child) = command.spawn() {
2002 /// child.kill().expect("command couldn't be killed");
2003 /// } else {
2004 /// println!("yes command didn't start");
2005 /// }
2006 /// ```
2007 ///
2008 /// [`ErrorKind`]: io::ErrorKind
2009 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
2010 #[stable(feature = "process", since = "1.0.0")]
kill(&mut self) -> io::Result<()>2011 pub fn kill(&mut self) -> io::Result<()> {
2012 self.handle.kill()
2013 }
2014
2015 /// Returns the OS-assigned process identifier associated with this child.
2016 ///
2017 /// # Examples
2018 ///
2019 /// Basic usage:
2020 ///
2021 /// ```no_run
2022 /// use std::process::Command;
2023 ///
2024 /// let mut command = Command::new("ls");
2025 /// if let Ok(child) = command.spawn() {
2026 /// println!("Child's ID is {}", child.id());
2027 /// } else {
2028 /// println!("ls command didn't start");
2029 /// }
2030 /// ```
2031 #[must_use]
2032 #[stable(feature = "process_id", since = "1.3.0")]
id(&self) -> u322033 pub fn id(&self) -> u32 {
2034 self.handle.id()
2035 }
2036
2037 /// Waits for the child to exit completely, returning the status that it
2038 /// exited with. This function will continue to have the same return value
2039 /// after it has been called at least once.
2040 ///
2041 /// The stdin handle to the child process, if any, will be closed
2042 /// before waiting. This helps avoid deadlock: it ensures that the
2043 /// child does not block waiting for input from the parent, while
2044 /// the parent waits for the child to exit.
2045 ///
2046 /// # Examples
2047 ///
2048 /// Basic usage:
2049 ///
2050 /// ```no_run
2051 /// use std::process::Command;
2052 ///
2053 /// let mut command = Command::new("ls");
2054 /// if let Ok(mut child) = command.spawn() {
2055 /// child.wait().expect("command wasn't running");
2056 /// println!("Child has finished its execution!");
2057 /// } else {
2058 /// println!("ls command didn't start");
2059 /// }
2060 /// ```
2061 #[stable(feature = "process", since = "1.0.0")]
wait(&mut self) -> io::Result<ExitStatus>2062 pub fn wait(&mut self) -> io::Result<ExitStatus> {
2063 drop(self.stdin.take());
2064 self.handle.wait().map(ExitStatus)
2065 }
2066
2067 /// Attempts to collect the exit status of the child if it has already
2068 /// exited.
2069 ///
2070 /// This function will not block the calling thread and will only
2071 /// check to see if the child process has exited or not. If the child has
2072 /// exited then on Unix the process ID is reaped. This function is
2073 /// guaranteed to repeatedly return a successful exit status so long as the
2074 /// child has already exited.
2075 ///
2076 /// If the child has exited, then `Ok(Some(status))` is returned. If the
2077 /// exit status is not available at this time then `Ok(None)` is returned.
2078 /// If an error occurs, then that error is returned.
2079 ///
2080 /// Note that unlike `wait`, this function will not attempt to drop stdin.
2081 ///
2082 /// # Examples
2083 ///
2084 /// Basic usage:
2085 ///
2086 /// ```no_run
2087 /// use std::process::Command;
2088 ///
2089 /// let mut child = Command::new("ls").spawn().unwrap();
2090 ///
2091 /// match child.try_wait() {
2092 /// Ok(Some(status)) => println!("exited with: {status}"),
2093 /// Ok(None) => {
2094 /// println!("status not ready yet, let's really wait");
2095 /// let res = child.wait();
2096 /// println!("result: {res:?}");
2097 /// }
2098 /// Err(e) => println!("error attempting to wait: {e}"),
2099 /// }
2100 /// ```
2101 #[stable(feature = "process_try_wait", since = "1.18.0")]
try_wait(&mut self) -> io::Result<Option<ExitStatus>>2102 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
2103 Ok(self.handle.try_wait()?.map(ExitStatus))
2104 }
2105
2106 /// Simultaneously waits for the child to exit and collect all remaining
2107 /// output on the stdout/stderr handles, returning an `Output`
2108 /// instance.
2109 ///
2110 /// The stdin handle to the child process, if any, will be closed
2111 /// before waiting. This helps avoid deadlock: it ensures that the
2112 /// child does not block waiting for input from the parent, while
2113 /// the parent waits for the child to exit.
2114 ///
2115 /// By default, stdin, stdout and stderr are inherited from the parent.
2116 /// In order to capture the output into this `Result<Output>` it is
2117 /// necessary to create new pipes between parent and child. Use
2118 /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
2119 ///
2120 /// # Examples
2121 ///
2122 /// ```should_panic
2123 /// use std::process::{Command, Stdio};
2124 ///
2125 /// let child = Command::new("/bin/cat")
2126 /// .arg("file.txt")
2127 /// .stdout(Stdio::piped())
2128 /// .spawn()
2129 /// .expect("failed to execute child");
2130 ///
2131 /// let output = child
2132 /// .wait_with_output()
2133 /// .expect("failed to wait on child");
2134 ///
2135 /// assert!(output.status.success());
2136 /// ```
2137 ///
2138 #[stable(feature = "process", since = "1.0.0")]
wait_with_output(mut self) -> io::Result<Output>2139 pub fn wait_with_output(mut self) -> io::Result<Output> {
2140 drop(self.stdin.take());
2141
2142 let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
2143 match (self.stdout.take(), self.stderr.take()) {
2144 (None, None) => {}
2145 (Some(mut out), None) => {
2146 let res = out.read_to_end(&mut stdout);
2147 res.unwrap();
2148 }
2149 (None, Some(mut err)) => {
2150 let res = err.read_to_end(&mut stderr);
2151 res.unwrap();
2152 }
2153 (Some(out), Some(err)) => {
2154 let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
2155 res.unwrap();
2156 }
2157 }
2158
2159 let status = self.wait()?;
2160 Ok(Output { status, stdout, stderr })
2161 }
2162 }
2163
2164 /// Terminates the current process with the specified exit code.
2165 ///
2166 /// This function will never return and will immediately terminate the current
2167 /// process. The exit code is passed through to the underlying OS and will be
2168 /// available for consumption by another process.
2169 ///
2170 /// Note that because this function never returns, and that it terminates the
2171 /// process, no destructors on the current stack or any other thread's stack
2172 /// will be run. If a clean shutdown is needed it is recommended to only call
2173 /// this function at a known point where there are no more destructors left
2174 /// to run; or, preferably, simply return a type implementing [`Termination`]
2175 /// (such as [`ExitCode`] or `Result`) from the `main` function and avoid this
2176 /// function altogether:
2177 ///
2178 /// ```
2179 /// # use std::io::Error as MyError;
2180 /// fn main() -> Result<(), MyError> {
2181 /// // ...
2182 /// Ok(())
2183 /// }
2184 /// ```
2185 ///
2186 /// ## Platform-specific behavior
2187 ///
2188 /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
2189 /// will be visible to a parent process inspecting the exit code. On most
2190 /// Unix-like platforms, only the eight least-significant bits are considered.
2191 ///
2192 /// For example, the exit code for this example will be `0` on Linux, but `256`
2193 /// on Windows:
2194 ///
2195 /// ```no_run
2196 /// use std::process;
2197 ///
2198 /// process::exit(0x0100);
2199 /// ```
2200 #[stable(feature = "rust1", since = "1.0.0")]
exit(code: i32) -> !2201 pub fn exit(code: i32) -> ! {
2202 crate::rt::cleanup();
2203 crate::sys::os::exit(code)
2204 }
2205
2206 /// Terminates the process in an abnormal fashion.
2207 ///
2208 /// The function will never return and will immediately terminate the current
2209 /// process in a platform specific "abnormal" manner.
2210 ///
2211 /// Note that because this function never returns, and that it terminates the
2212 /// process, no destructors on the current stack or any other thread's stack
2213 /// will be run.
2214 ///
2215 /// Rust IO buffers (eg, from `BufWriter`) will not be flushed.
2216 /// Likewise, C stdio buffers will (on most platforms) not be flushed.
2217 ///
2218 /// This is in contrast to the default behaviour of [`panic!`] which unwinds
2219 /// the current thread's stack and calls all destructors.
2220 /// When `panic="abort"` is set, either as an argument to `rustc` or in a
2221 /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
2222 /// [`panic!`] will still call the [panic hook] while `abort` will not.
2223 ///
2224 /// If a clean shutdown is needed it is recommended to only call
2225 /// this function at a known point where there are no more destructors left
2226 /// to run.
2227 ///
2228 /// The process's termination will be similar to that from the C `abort()`
2229 /// function. On Unix, the process will terminate with signal `SIGABRT`, which
2230 /// typically means that the shell prints "Aborted".
2231 ///
2232 /// # Examples
2233 ///
2234 /// ```no_run
2235 /// use std::process;
2236 ///
2237 /// fn main() {
2238 /// println!("aborting");
2239 ///
2240 /// process::abort();
2241 ///
2242 /// // execution never gets here
2243 /// }
2244 /// ```
2245 ///
2246 /// The `abort` function terminates the process, so the destructor will not
2247 /// get run on the example below:
2248 ///
2249 /// ```no_run
2250 /// use std::process;
2251 ///
2252 /// struct HasDrop;
2253 ///
2254 /// impl Drop for HasDrop {
2255 /// fn drop(&mut self) {
2256 /// println!("This will never be printed!");
2257 /// }
2258 /// }
2259 ///
2260 /// fn main() {
2261 /// let _x = HasDrop;
2262 /// process::abort();
2263 /// // the destructor implemented for HasDrop will never get run
2264 /// }
2265 /// ```
2266 ///
2267 /// [panic hook]: crate::panic::set_hook
2268 #[stable(feature = "process_abort", since = "1.17.0")]
2269 #[cold]
abort() -> !2270 pub fn abort() -> ! {
2271 crate::sys::abort_internal();
2272 }
2273
2274 /// Returns the OS-assigned process identifier associated with this process.
2275 ///
2276 /// # Examples
2277 ///
2278 /// Basic usage:
2279 ///
2280 /// ```no_run
2281 /// use std::process;
2282 ///
2283 /// println!("My pid is {}", process::id());
2284 /// ```
2285 ///
2286 ///
2287 #[must_use]
2288 #[stable(feature = "getpid", since = "1.26.0")]
id() -> u322289 pub fn id() -> u32 {
2290 crate::sys::os::getpid()
2291 }
2292
2293 /// A trait for implementing arbitrary return types in the `main` function.
2294 ///
2295 /// The C-main function only supports returning integers.
2296 /// So, every type implementing the `Termination` trait has to be converted
2297 /// to an integer.
2298 ///
2299 /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
2300 /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
2301 ///
2302 /// Because different runtimes have different specifications on the return value
2303 /// of the `main` function, this trait is likely to be available only on
2304 /// standard library's runtime for convenience. Other runtimes are not required
2305 /// to provide similar functionality.
2306 #[cfg_attr(not(test), lang = "termination")]
2307 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2308 #[rustc_on_unimplemented(on(
2309 cause = "MainFunctionType",
2310 message = "`main` has invalid return type `{Self}`",
2311 label = "`main` can only return types that implement `{Termination}`"
2312 ))]
2313 pub trait Termination {
2314 /// Is called to get the representation of the value as status code.
2315 /// This status code is returned to the operating system.
2316 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
report(self) -> ExitCode2317 fn report(self) -> ExitCode;
2318 }
2319
2320 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2321 impl Termination for () {
2322 #[inline]
report(self) -> ExitCode2323 fn report(self) -> ExitCode {
2324 ExitCode::SUCCESS
2325 }
2326 }
2327
2328 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2329 impl Termination for ! {
report(self) -> ExitCode2330 fn report(self) -> ExitCode {
2331 self
2332 }
2333 }
2334
2335 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2336 impl Termination for Infallible {
report(self) -> ExitCode2337 fn report(self) -> ExitCode {
2338 match self {}
2339 }
2340 }
2341
2342 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2343 impl Termination for ExitCode {
2344 #[inline]
report(self) -> ExitCode2345 fn report(self) -> ExitCode {
2346 self
2347 }
2348 }
2349
2350 #[stable(feature = "termination_trait_lib", since = "1.61.0")]
2351 impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
report(self) -> ExitCode2352 fn report(self) -> ExitCode {
2353 match self {
2354 Ok(val) => val.report(),
2355 Err(err) => {
2356 io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));
2357 ExitCode::FAILURE
2358 }
2359 }
2360 }
2361 }
2362