PageRenderTime 69ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/src/libstd/process.rs

https://gitlab.com/jianglu/rust
Rust | 1600 lines | 535 code | 101 blank | 964 comment | 46 complexity | abda047c2d6fd670e904037a244e532a MD5 | raw file
  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.
  4. //
  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.
  10. //! A module for working with processes.
  11. //!
  12. //! This module is mostly concerned with spawning and interacting with child
  13. //! processes, but it also provides [`abort`] and [`exit`] for terminating the
  14. //! current process.
  15. //!
  16. //! # Spawning a process
  17. //!
  18. //! The [`Command`] struct is used to configure and spawn processes:
  19. //!
  20. //! ```
  21. //! use std::process::Command;
  22. //!
  23. //! let output = Command::new("echo")
  24. //! .arg("Hello world")
  25. //! .output()
  26. //! .expect("Failed to execute command");
  27. //!
  28. //! assert_eq!(b"Hello world\n", output.stdout.as_slice());
  29. //! ```
  30. //!
  31. //! Several methods on [`Command`], such as [`spawn`] or [`output`], can be used
  32. //! to spawn a process. In particular, [`output`] spawns the child process and
  33. //! waits until the process terminates, while [`spawn`] will return a [`Child`]
  34. //! that represents the spawned child process.
  35. //!
  36. //! # Handling I/O
  37. //!
  38. //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be
  39. //! configured by passing an [`Stdio`] to the corresponding method on
  40. //! [`Command`]. Once spawned, they can be accessed from the [`Child`]. For
  41. //! example, piping output from one command into another command can be done
  42. //! like so:
  43. //!
  44. //! ```no_run
  45. //! use std::process::{Command, Stdio};
  46. //!
  47. //! // stdout must be configured with `Stdio::piped` in order to use
  48. //! // `echo_child.stdout`
  49. //! let echo_child = Command::new("echo")
  50. //! .arg("Oh no, a tpyo!")
  51. //! .stdout(Stdio::piped())
  52. //! .spawn()
  53. //! .expect("Failed to start echo process");
  54. //!
  55. //! // Note that `echo_child` is moved here, but we won't be needing
  56. //! // `echo_child` anymore
  57. //! let echo_out = echo_child.stdout.expect("Failed to open echo stdout");
  58. //!
  59. //! let mut sed_child = Command::new("sed")
  60. //! .arg("s/tpyo/typo/")
  61. //! .stdin(Stdio::from(echo_out))
  62. //! .stdout(Stdio::piped())
  63. //! .spawn()
  64. //! .expect("Failed to start sed process");
  65. //!
  66. //! let output = sed_child.wait_with_output().expect("Failed to wait on sed");
  67. //! assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());
  68. //! ```
  69. //!
  70. //! Note that [`ChildStderr`] and [`ChildStdout`] implement [`Read`] and
  71. //! [`ChildStdin`] implements [`Write`]:
  72. //!
  73. //! ```no_run
  74. //! use std::process::{Command, Stdio};
  75. //! use std::io::Write;
  76. //!
  77. //! let mut child = Command::new("/bin/cat")
  78. //! .stdin(Stdio::piped())
  79. //! .stdout(Stdio::piped())
  80. //! .spawn()
  81. //! .expect("failed to execute child");
  82. //!
  83. //! {
  84. //! // limited borrow of stdin
  85. //! let stdin = child.stdin.as_mut().expect("failed to get stdin");
  86. //! stdin.write_all(b"test").expect("failed to write to stdin");
  87. //! }
  88. //!
  89. //! let output = child
  90. //! .wait_with_output()
  91. //! .expect("failed to wait on child");
  92. //!
  93. //! assert_eq!(b"test", output.stdout.as_slice());
  94. //! ```
  95. //!
  96. //! [`abort`]: fn.abort.html
  97. //! [`exit`]: fn.exit.html
  98. //!
  99. //! [`Command`]: struct.Command.html
  100. //! [`spawn`]: struct.Command.html#method.spawn
  101. //! [`output`]: struct.Command.html#method.output
  102. //!
  103. //! [`Child`]: struct.Child.html
  104. //! [`ChildStdin`]: struct.ChildStdin.html
  105. //! [`ChildStdout`]: struct.ChildStdout.html
  106. //! [`ChildStderr`]: struct.ChildStderr.html
  107. //! [`Stdio`]: struct.Stdio.html
  108. //!
  109. //! [`stdout`]: struct.Command.html#method.stdout
  110. //! [`stdin`]: struct.Command.html#method.stdin
  111. //! [`stderr`]: struct.Command.html#method.stderr
  112. //!
  113. //! [`Write`]: ../io/trait.Write.html
  114. //! [`Read`]: ../io/trait.Read.html
  115. #![stable(feature = "process", since = "1.0.0")]
  116. use io::prelude::*;
  117. use ffi::OsStr;
  118. use fmt;
  119. use fs;
  120. use io::{self, Initializer};
  121. use path::Path;
  122. use str;
  123. use sys::pipe::{read2, AnonPipe};
  124. use sys::process as imp;
  125. use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
  126. /// Representation of a running or exited child process.
  127. ///
  128. /// This structure is used to represent and manage child processes. A child
  129. /// process is created via the [`Command`] struct, which configures the
  130. /// spawning process and can itself be constructed using a builder-style
  131. /// interface.
  132. ///
  133. /// There is no implementation of [`Drop`] for child processes,
  134. /// so if you do not ensure the `Child` has exited then it will continue to
  135. /// run, even after the `Child` handle to the child process has gone out of
  136. /// scope.
  137. ///
  138. /// Calling [`wait`](#method.wait) (or other functions that wrap around it) will make
  139. /// the parent process wait until the child has actually exited before
  140. /// continuing.
  141. ///
  142. /// # Examples
  143. ///
  144. /// ```should_panic
  145. /// use std::process::Command;
  146. ///
  147. /// let mut child = Command::new("/bin/cat")
  148. /// .arg("file.txt")
  149. /// .spawn()
  150. /// .expect("failed to execute child");
  151. ///
  152. /// let ecode = child.wait()
  153. /// .expect("failed to wait on child");
  154. ///
  155. /// assert!(ecode.success());
  156. /// ```
  157. ///
  158. /// [`Command`]: struct.Command.html
  159. /// [`Drop`]: ../../core/ops/trait.Drop.html
  160. /// [`wait`]: #method.wait
  161. #[stable(feature = "process", since = "1.0.0")]
  162. pub struct Child {
  163. handle: imp::Process,
  164. /// The handle for writing to the child's standard input (stdin), if it has
  165. /// been captured.
  166. #[stable(feature = "process", since = "1.0.0")]
  167. pub stdin: Option<ChildStdin>,
  168. /// The handle for reading from the child's standard output (stdout), if it
  169. /// has been captured.
  170. #[stable(feature = "process", since = "1.0.0")]
  171. pub stdout: Option<ChildStdout>,
  172. /// The handle for reading from the child's standard error (stderr), if it
  173. /// has been captured.
  174. #[stable(feature = "process", since = "1.0.0")]
  175. pub stderr: Option<ChildStderr>,
  176. }
  177. impl AsInner<imp::Process> for Child {
  178. fn as_inner(&self) -> &imp::Process { &self.handle }
  179. }
  180. impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
  181. fn from_inner((handle, io): (imp::Process, imp::StdioPipes)) -> Child {
  182. Child {
  183. handle,
  184. stdin: io.stdin.map(ChildStdin::from_inner),
  185. stdout: io.stdout.map(ChildStdout::from_inner),
  186. stderr: io.stderr.map(ChildStderr::from_inner),
  187. }
  188. }
  189. }
  190. impl IntoInner<imp::Process> for Child {
  191. fn into_inner(self) -> imp::Process { self.handle }
  192. }
  193. #[stable(feature = "std_debug", since = "1.16.0")]
  194. impl fmt::Debug for Child {
  195. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  196. f.debug_struct("Child")
  197. .field("stdin", &self.stdin)
  198. .field("stdout", &self.stdout)
  199. .field("stderr", &self.stderr)
  200. .finish()
  201. }
  202. }
  203. /// A handle to a child process's standard input (stdin).
  204. ///
  205. /// This struct is used in the [`stdin`] field on [`Child`].
  206. ///
  207. /// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
  208. /// file handle will be closed. If the child process was blocked on input prior
  209. /// to being dropped, it will become unblocked after dropping.
  210. ///
  211. /// [`Child`]: struct.Child.html
  212. /// [`stdin`]: struct.Child.html#structfield.stdin
  213. /// [dropped]: ../ops/trait.Drop.html
  214. #[stable(feature = "process", since = "1.0.0")]
  215. pub struct ChildStdin {
  216. inner: AnonPipe
  217. }
  218. #[stable(feature = "process", since = "1.0.0")]
  219. impl Write for ChildStdin {
  220. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  221. self.inner.write(buf)
  222. }
  223. fn flush(&mut self) -> io::Result<()> {
  224. Ok(())
  225. }
  226. }
  227. impl AsInner<AnonPipe> for ChildStdin {
  228. fn as_inner(&self) -> &AnonPipe { &self.inner }
  229. }
  230. impl IntoInner<AnonPipe> for ChildStdin {
  231. fn into_inner(self) -> AnonPipe { self.inner }
  232. }
  233. impl FromInner<AnonPipe> for ChildStdin {
  234. fn from_inner(pipe: AnonPipe) -> ChildStdin {
  235. ChildStdin { inner: pipe }
  236. }
  237. }
  238. #[stable(feature = "std_debug", since = "1.16.0")]
  239. impl fmt::Debug for ChildStdin {
  240. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  241. f.pad("ChildStdin { .. }")
  242. }
  243. }
  244. /// A handle to a child process's standard output (stdout).
  245. ///
  246. /// This struct is used in the [`stdout`] field on [`Child`].
  247. ///
  248. /// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
  249. /// underlying file handle will be closed.
  250. ///
  251. /// [`Child`]: struct.Child.html
  252. /// [`stdout`]: struct.Child.html#structfield.stdout
  253. /// [dropped]: ../ops/trait.Drop.html
  254. #[stable(feature = "process", since = "1.0.0")]
  255. pub struct ChildStdout {
  256. inner: AnonPipe
  257. }
  258. #[stable(feature = "process", since = "1.0.0")]
  259. impl Read for ChildStdout {
  260. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  261. self.inner.read(buf)
  262. }
  263. #[inline]
  264. unsafe fn initializer(&self) -> Initializer {
  265. Initializer::nop()
  266. }
  267. }
  268. impl AsInner<AnonPipe> for ChildStdout {
  269. fn as_inner(&self) -> &AnonPipe { &self.inner }
  270. }
  271. impl IntoInner<AnonPipe> for ChildStdout {
  272. fn into_inner(self) -> AnonPipe { self.inner }
  273. }
  274. impl FromInner<AnonPipe> for ChildStdout {
  275. fn from_inner(pipe: AnonPipe) -> ChildStdout {
  276. ChildStdout { inner: pipe }
  277. }
  278. }
  279. #[stable(feature = "std_debug", since = "1.16.0")]
  280. impl fmt::Debug for ChildStdout {
  281. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  282. f.pad("ChildStdout { .. }")
  283. }
  284. }
  285. /// A handle to a child process's stderr.
  286. ///
  287. /// This struct is used in the [`stderr`] field on [`Child`].
  288. ///
  289. /// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
  290. /// underlying file handle will be closed.
  291. ///
  292. /// [`Child`]: struct.Child.html
  293. /// [`stderr`]: struct.Child.html#structfield.stderr
  294. /// [dropped]: ../ops/trait.Drop.html
  295. #[stable(feature = "process", since = "1.0.0")]
  296. pub struct ChildStderr {
  297. inner: AnonPipe
  298. }
  299. #[stable(feature = "process", since = "1.0.0")]
  300. impl Read for ChildStderr {
  301. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  302. self.inner.read(buf)
  303. }
  304. #[inline]
  305. unsafe fn initializer(&self) -> Initializer {
  306. Initializer::nop()
  307. }
  308. }
  309. impl AsInner<AnonPipe> for ChildStderr {
  310. fn as_inner(&self) -> &AnonPipe { &self.inner }
  311. }
  312. impl IntoInner<AnonPipe> for ChildStderr {
  313. fn into_inner(self) -> AnonPipe { self.inner }
  314. }
  315. impl FromInner<AnonPipe> for ChildStderr {
  316. fn from_inner(pipe: AnonPipe) -> ChildStderr {
  317. ChildStderr { inner: pipe }
  318. }
  319. }
  320. #[stable(feature = "std_debug", since = "1.16.0")]
  321. impl fmt::Debug for ChildStderr {
  322. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  323. f.pad("ChildStderr { .. }")
  324. }
  325. }
  326. /// A process builder, providing fine-grained control
  327. /// over how a new process should be spawned.
  328. ///
  329. /// A default configuration can be
  330. /// generated using `Command::new(program)`, where `program` gives a path to the
  331. /// program to be executed. Additional builder methods allow the configuration
  332. /// to be changed (for example, by adding arguments) prior to spawning:
  333. ///
  334. /// ```
  335. /// use std::process::Command;
  336. ///
  337. /// let output = if cfg!(target_os = "windows") {
  338. /// Command::new("cmd")
  339. /// .args(&["/C", "echo hello"])
  340. /// .output()
  341. /// .expect("failed to execute process")
  342. /// } else {
  343. /// Command::new("sh")
  344. /// .arg("-c")
  345. /// .arg("echo hello")
  346. /// .output()
  347. /// .expect("failed to execute process")
  348. /// };
  349. ///
  350. /// let hello = output.stdout;
  351. /// ```
  352. #[stable(feature = "process", since = "1.0.0")]
  353. pub struct Command {
  354. inner: imp::Command,
  355. }
  356. impl Command {
  357. /// Constructs a new `Command` for launching the program at
  358. /// path `program`, with the following default configuration:
  359. ///
  360. /// * No arguments to the program
  361. /// * Inherit the current process's environment
  362. /// * Inherit the current process's working directory
  363. /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
  364. ///
  365. /// Builder methods are provided to change these defaults and
  366. /// otherwise configure the process.
  367. ///
  368. /// If `program` is not an absolute path, the `PATH` will be searched in
  369. /// an OS-defined way.
  370. ///
  371. /// The search path to be used may be controlled by setting the
  372. /// `PATH` environment variable on the Command,
  373. /// but this has some implementation limitations on Windows
  374. /// (see <https://github.com/rust-lang/rust/issues/37519>).
  375. ///
  376. /// # Examples
  377. ///
  378. /// Basic usage:
  379. ///
  380. /// ```no_run
  381. /// use std::process::Command;
  382. ///
  383. /// Command::new("sh")
  384. /// .spawn()
  385. /// .expect("sh command failed to start");
  386. /// ```
  387. #[stable(feature = "process", since = "1.0.0")]
  388. pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
  389. Command { inner: imp::Command::new(program.as_ref()) }
  390. }
  391. /// Add an argument to pass to the program.
  392. ///
  393. /// Only one argument can be passed per use. So instead of:
  394. ///
  395. /// ```no_run
  396. /// # std::process::Command::new("sh")
  397. /// .arg("-C /path/to/repo")
  398. /// # ;
  399. /// ```
  400. ///
  401. /// usage would be:
  402. ///
  403. /// ```no_run
  404. /// # std::process::Command::new("sh")
  405. /// .arg("-C")
  406. /// .arg("/path/to/repo")
  407. /// # ;
  408. /// ```
  409. ///
  410. /// To pass multiple arguments see [`args`].
  411. ///
  412. /// [`args`]: #method.args
  413. ///
  414. /// # Examples
  415. ///
  416. /// Basic usage:
  417. ///
  418. /// ```no_run
  419. /// use std::process::Command;
  420. ///
  421. /// Command::new("ls")
  422. /// .arg("-l")
  423. /// .arg("-a")
  424. /// .spawn()
  425. /// .expect("ls command failed to start");
  426. /// ```
  427. #[stable(feature = "process", since = "1.0.0")]
  428. pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
  429. self.inner.arg(arg.as_ref());
  430. self
  431. }
  432. /// Add multiple arguments to pass to the program.
  433. ///
  434. /// To pass a single argument see [`arg`].
  435. ///
  436. /// [`arg`]: #method.arg
  437. ///
  438. /// # Examples
  439. ///
  440. /// Basic usage:
  441. ///
  442. /// ```no_run
  443. /// use std::process::Command;
  444. ///
  445. /// Command::new("ls")
  446. /// .args(&["-l", "-a"])
  447. /// .spawn()
  448. /// .expect("ls command failed to start");
  449. /// ```
  450. #[stable(feature = "process", since = "1.0.0")]
  451. pub fn args<I, S>(&mut self, args: I) -> &mut Command
  452. where I: IntoIterator<Item=S>, S: AsRef<OsStr>
  453. {
  454. for arg in args {
  455. self.arg(arg.as_ref());
  456. }
  457. self
  458. }
  459. /// Inserts or updates an environment variable mapping.
  460. ///
  461. /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
  462. /// and case-sensitive on all other platforms.
  463. ///
  464. /// # Examples
  465. ///
  466. /// Basic usage:
  467. ///
  468. /// ```no_run
  469. /// use std::process::Command;
  470. ///
  471. /// Command::new("ls")
  472. /// .env("PATH", "/bin")
  473. /// .spawn()
  474. /// .expect("ls command failed to start");
  475. /// ```
  476. #[stable(feature = "process", since = "1.0.0")]
  477. pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
  478. where K: AsRef<OsStr>, V: AsRef<OsStr>
  479. {
  480. self.inner.env_mut().set(key.as_ref(), val.as_ref());
  481. self
  482. }
  483. /// Add or update multiple environment variable mappings.
  484. ///
  485. /// # Examples
  486. ///
  487. /// Basic usage:
  488. ///
  489. /// ```no_run
  490. /// use std::process::{Command, Stdio};
  491. /// use std::env;
  492. /// use std::collections::HashMap;
  493. ///
  494. /// let filtered_env : HashMap<String, String> =
  495. /// env::vars().filter(|&(ref k, _)|
  496. /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
  497. /// ).collect();
  498. ///
  499. /// Command::new("printenv")
  500. /// .stdin(Stdio::null())
  501. /// .stdout(Stdio::inherit())
  502. /// .env_clear()
  503. /// .envs(&filtered_env)
  504. /// .spawn()
  505. /// .expect("printenv failed to start");
  506. /// ```
  507. #[stable(feature = "command_envs", since = "1.19.0")]
  508. pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
  509. where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
  510. {
  511. for (ref key, ref val) in vars {
  512. self.inner.env_mut().set(key.as_ref(), val.as_ref());
  513. }
  514. self
  515. }
  516. /// Removes an environment variable mapping.
  517. ///
  518. /// # Examples
  519. ///
  520. /// Basic usage:
  521. ///
  522. /// ```no_run
  523. /// use std::process::Command;
  524. ///
  525. /// Command::new("ls")
  526. /// .env_remove("PATH")
  527. /// .spawn()
  528. /// .expect("ls command failed to start");
  529. /// ```
  530. #[stable(feature = "process", since = "1.0.0")]
  531. pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
  532. self.inner.env_mut().remove(key.as_ref());
  533. self
  534. }
  535. /// Clears the entire environment map for the child process.
  536. ///
  537. /// # Examples
  538. ///
  539. /// Basic usage:
  540. ///
  541. /// ```no_run
  542. /// use std::process::Command;
  543. ///
  544. /// Command::new("ls")
  545. /// .env_clear()
  546. /// .spawn()
  547. /// .expect("ls command failed to start");
  548. /// ```
  549. #[stable(feature = "process", since = "1.0.0")]
  550. pub fn env_clear(&mut self) -> &mut Command {
  551. self.inner.env_mut().clear();
  552. self
  553. }
  554. /// Sets the working directory for the child process.
  555. ///
  556. /// # Examples
  557. ///
  558. /// Basic usage:
  559. ///
  560. /// ```no_run
  561. /// use std::process::Command;
  562. ///
  563. /// Command::new("ls")
  564. /// .current_dir("/bin")
  565. /// .spawn()
  566. /// .expect("ls command failed to start");
  567. /// ```
  568. #[stable(feature = "process", since = "1.0.0")]
  569. pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
  570. self.inner.cwd(dir.as_ref().as_ref());
  571. self
  572. }
  573. /// Configuration for the child process's standard input (stdin) handle.
  574. ///
  575. /// Defaults to [`inherit`] when used with `spawn` or `status`, and
  576. /// defaults to [`piped`] when used with `output`.
  577. ///
  578. /// [`inherit`]: struct.Stdio.html#method.inherit
  579. /// [`piped`]: struct.Stdio.html#method.piped
  580. ///
  581. /// # Examples
  582. ///
  583. /// Basic usage:
  584. ///
  585. /// ```no_run
  586. /// use std::process::{Command, Stdio};
  587. ///
  588. /// Command::new("ls")
  589. /// .stdin(Stdio::null())
  590. /// .spawn()
  591. /// .expect("ls command failed to start");
  592. /// ```
  593. #[stable(feature = "process", since = "1.0.0")]
  594. pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
  595. self.inner.stdin(cfg.into().0);
  596. self
  597. }
  598. /// Configuration for the child process's standard output (stdout) handle.
  599. ///
  600. /// Defaults to [`inherit`] when used with `spawn` or `status`, and
  601. /// defaults to [`piped`] when used with `output`.
  602. ///
  603. /// [`inherit`]: struct.Stdio.html#method.inherit
  604. /// [`piped`]: struct.Stdio.html#method.piped
  605. ///
  606. /// # Examples
  607. ///
  608. /// Basic usage:
  609. ///
  610. /// ```no_run
  611. /// use std::process::{Command, Stdio};
  612. ///
  613. /// Command::new("ls")
  614. /// .stdout(Stdio::null())
  615. /// .spawn()
  616. /// .expect("ls command failed to start");
  617. /// ```
  618. #[stable(feature = "process", since = "1.0.0")]
  619. pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
  620. self.inner.stdout(cfg.into().0);
  621. self
  622. }
  623. /// Configuration for the child process's standard error (stderr) handle.
  624. ///
  625. /// Defaults to [`inherit`] when used with `spawn` or `status`, and
  626. /// defaults to [`piped`] when used with `output`.
  627. ///
  628. /// [`inherit`]: struct.Stdio.html#method.inherit
  629. /// [`piped`]: struct.Stdio.html#method.piped
  630. ///
  631. /// # Examples
  632. ///
  633. /// Basic usage:
  634. ///
  635. /// ```no_run
  636. /// use std::process::{Command, Stdio};
  637. ///
  638. /// Command::new("ls")
  639. /// .stderr(Stdio::null())
  640. /// .spawn()
  641. /// .expect("ls command failed to start");
  642. /// ```
  643. #[stable(feature = "process", since = "1.0.0")]
  644. pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
  645. self.inner.stderr(cfg.into().0);
  646. self
  647. }
  648. /// Executes the command as a child process, returning a handle to it.
  649. ///
  650. /// By default, stdin, stdout and stderr are inherited from the parent.
  651. ///
  652. /// # Examples
  653. ///
  654. /// Basic usage:
  655. ///
  656. /// ```no_run
  657. /// use std::process::Command;
  658. ///
  659. /// Command::new("ls")
  660. /// .spawn()
  661. /// .expect("ls command failed to start");
  662. /// ```
  663. #[stable(feature = "process", since = "1.0.0")]
  664. pub fn spawn(&mut self) -> io::Result<Child> {
  665. self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
  666. }
  667. /// Executes the command as a child process, waiting for it to finish and
  668. /// collecting all of its output.
  669. ///
  670. /// By default, stdout and stderr are captured (and used to provide the
  671. /// resulting output). Stdin is not inherited from the parent and any
  672. /// attempt by the child process to read from the stdin stream will result
  673. /// in the stream immediately closing.
  674. ///
  675. /// # Examples
  676. ///
  677. /// ```should_panic
  678. /// use std::process::Command;
  679. /// let output = Command::new("/bin/cat")
  680. /// .arg("file.txt")
  681. /// .output()
  682. /// .expect("failed to execute process");
  683. ///
  684. /// println!("status: {}", output.status);
  685. /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
  686. /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
  687. ///
  688. /// assert!(output.status.success());
  689. /// ```
  690. #[stable(feature = "process", since = "1.0.0")]
  691. pub fn output(&mut self) -> io::Result<Output> {
  692. self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
  693. .and_then(|p| p.wait_with_output())
  694. }
  695. /// Executes a command as a child process, waiting for it to finish and
  696. /// collecting its exit status.
  697. ///
  698. /// By default, stdin, stdout and stderr are inherited from the parent.
  699. ///
  700. /// # Examples
  701. ///
  702. /// ```should_panic
  703. /// use std::process::Command;
  704. ///
  705. /// let status = Command::new("/bin/cat")
  706. /// .arg("file.txt")
  707. /// .status()
  708. /// .expect("failed to execute process");
  709. ///
  710. /// println!("process exited with: {}", status);
  711. ///
  712. /// assert!(status.success());
  713. /// ```
  714. #[stable(feature = "process", since = "1.0.0")]
  715. pub fn status(&mut self) -> io::Result<ExitStatus> {
  716. self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
  717. .and_then(|mut p| p.wait())
  718. }
  719. }
  720. #[stable(feature = "rust1", since = "1.0.0")]
  721. impl fmt::Debug for Command {
  722. /// Format the program and arguments of a Command for display. Any
  723. /// non-utf8 data is lossily converted using the utf8 replacement
  724. /// character.
  725. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  726. self.inner.fmt(f)
  727. }
  728. }
  729. impl AsInner<imp::Command> for Command {
  730. fn as_inner(&self) -> &imp::Command { &self.inner }
  731. }
  732. impl AsInnerMut<imp::Command> for Command {
  733. fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
  734. }
  735. /// The output of a finished process.
  736. ///
  737. /// This is returned in a Result by either the [`output`] method of a
  738. /// [`Command`], or the [`wait_with_output`] method of a [`Child`]
  739. /// process.
  740. ///
  741. /// [`Command`]: struct.Command.html
  742. /// [`Child`]: struct.Child.html
  743. /// [`output`]: struct.Command.html#method.output
  744. /// [`wait_with_output`]: struct.Child.html#method.wait_with_output
  745. #[derive(PartialEq, Eq, Clone)]
  746. #[stable(feature = "process", since = "1.0.0")]
  747. pub struct Output {
  748. /// The status (exit code) of the process.
  749. #[stable(feature = "process", since = "1.0.0")]
  750. pub status: ExitStatus,
  751. /// The data that the process wrote to stdout.
  752. #[stable(feature = "process", since = "1.0.0")]
  753. pub stdout: Vec<u8>,
  754. /// The data that the process wrote to stderr.
  755. #[stable(feature = "process", since = "1.0.0")]
  756. pub stderr: Vec<u8>,
  757. }
  758. // If either stderr or stdout are valid utf8 strings it prints the valid
  759. // strings, otherwise it prints the byte sequence instead
  760. #[stable(feature = "process_output_debug", since = "1.7.0")]
  761. impl fmt::Debug for Output {
  762. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  763. let stdout_utf8 = str::from_utf8(&self.stdout);
  764. let stdout_debug: &fmt::Debug = match stdout_utf8 {
  765. Ok(ref str) => str,
  766. Err(_) => &self.stdout
  767. };
  768. let stderr_utf8 = str::from_utf8(&self.stderr);
  769. let stderr_debug: &fmt::Debug = match stderr_utf8 {
  770. Ok(ref str) => str,
  771. Err(_) => &self.stderr
  772. };
  773. fmt.debug_struct("Output")
  774. .field("status", &self.status)
  775. .field("stdout", stdout_debug)
  776. .field("stderr", stderr_debug)
  777. .finish()
  778. }
  779. }
  780. /// Describes what to do with a standard I/O stream for a child process when
  781. /// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
  782. ///
  783. /// [`stdin`]: struct.Command.html#method.stdin
  784. /// [`stdout`]: struct.Command.html#method.stdout
  785. /// [`stderr`]: struct.Command.html#method.stderr
  786. /// [`Command`]: struct.Command.html
  787. #[stable(feature = "process", since = "1.0.0")]
  788. pub struct Stdio(imp::Stdio);
  789. impl Stdio {
  790. /// A new pipe should be arranged to connect the parent and child processes.
  791. ///
  792. /// # Examples
  793. ///
  794. /// With stdout:
  795. ///
  796. /// ```no_run
  797. /// use std::process::{Command, Stdio};
  798. ///
  799. /// let output = Command::new("echo")
  800. /// .arg("Hello, world!")
  801. /// .stdout(Stdio::piped())
  802. /// .output()
  803. /// .expect("Failed to execute command");
  804. ///
  805. /// assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
  806. /// // Nothing echoed to console
  807. /// ```
  808. ///
  809. /// With stdin:
  810. ///
  811. /// ```no_run
  812. /// use std::io::Write;
  813. /// use std::process::{Command, Stdio};
  814. ///
  815. /// let mut child = Command::new("rev")
  816. /// .stdin(Stdio::piped())
  817. /// .stdout(Stdio::piped())
  818. /// .spawn()
  819. /// .expect("Failed to spawn child process");
  820. ///
  821. /// {
  822. /// let mut stdin = child.stdin.as_mut().expect("Failed to open stdin");
  823. /// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
  824. /// }
  825. ///
  826. /// let output = child.wait_with_output().expect("Failed to read stdout");
  827. /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH\n");
  828. /// ```
  829. #[stable(feature = "process", since = "1.0.0")]
  830. pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
  831. /// The child inherits from the corresponding parent descriptor.
  832. ///
  833. /// # Examples
  834. ///
  835. /// With stdout:
  836. ///
  837. /// ```no_run
  838. /// use std::process::{Command, Stdio};
  839. ///
  840. /// let output = Command::new("echo")
  841. /// .arg("Hello, world!")
  842. /// .stdout(Stdio::inherit())
  843. /// .output()
  844. /// .expect("Failed to execute command");
  845. ///
  846. /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
  847. /// // "Hello, world!" echoed to console
  848. /// ```
  849. ///
  850. /// With stdin:
  851. ///
  852. /// ```no_run
  853. /// use std::process::{Command, Stdio};
  854. ///
  855. /// let output = Command::new("rev")
  856. /// .stdin(Stdio::inherit())
  857. /// .stdout(Stdio::piped())
  858. /// .output()
  859. /// .expect("Failed to execute command");
  860. ///
  861. /// println!("You piped in the reverse of: {}", String::from_utf8_lossy(&output.stdout));
  862. /// ```
  863. #[stable(feature = "process", since = "1.0.0")]
  864. pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
  865. /// This stream will be ignored. This is the equivalent of attaching the
  866. /// stream to `/dev/null`
  867. ///
  868. /// # Examples
  869. ///
  870. /// With stdout:
  871. ///
  872. /// ```no_run
  873. /// use std::process::{Command, Stdio};
  874. ///
  875. /// let output = Command::new("echo")
  876. /// .arg("Hello, world!")
  877. /// .stdout(Stdio::null())
  878. /// .output()
  879. /// .expect("Failed to execute command");
  880. ///
  881. /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
  882. /// // Nothing echoed to console
  883. /// ```
  884. ///
  885. /// With stdin:
  886. ///
  887. /// ```no_run
  888. /// use std::process::{Command, Stdio};
  889. ///
  890. /// let output = Command::new("rev")
  891. /// .stdin(Stdio::null())
  892. /// .stdout(Stdio::piped())
  893. /// .output()
  894. /// .expect("Failed to execute command");
  895. ///
  896. /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
  897. /// // Ignores any piped-in input
  898. /// ```
  899. #[stable(feature = "process", since = "1.0.0")]
  900. pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
  901. }
  902. impl FromInner<imp::Stdio> for Stdio {
  903. fn from_inner(inner: imp::Stdio) -> Stdio {
  904. Stdio(inner)
  905. }
  906. }
  907. #[stable(feature = "std_debug", since = "1.16.0")]
  908. impl fmt::Debug for Stdio {
  909. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  910. f.pad("Stdio { .. }")
  911. }
  912. }
  913. #[stable(feature = "stdio_from", since = "1.20.0")]
  914. impl From<ChildStdin> for Stdio {
  915. fn from(child: ChildStdin) -> Stdio {
  916. Stdio::from_inner(child.into_inner().into())
  917. }
  918. }
  919. #[stable(feature = "stdio_from", since = "1.20.0")]
  920. impl From<ChildStdout> for Stdio {
  921. fn from(child: ChildStdout) -> Stdio {
  922. Stdio::from_inner(child.into_inner().into())
  923. }
  924. }
  925. #[stable(feature = "stdio_from", since = "1.20.0")]
  926. impl From<ChildStderr> for Stdio {
  927. fn from(child: ChildStderr) -> Stdio {
  928. Stdio::from_inner(child.into_inner().into())
  929. }
  930. }
  931. #[stable(feature = "stdio_from", since = "1.20.0")]
  932. impl From<fs::File> for Stdio {
  933. fn from(file: fs::File) -> Stdio {
  934. Stdio::from_inner(file.into_inner().into())
  935. }
  936. }
  937. /// Describes the result of a process after it has terminated.
  938. ///
  939. /// This `struct` is used to represent the exit status of a child process.
  940. /// Child processes are created via the [`Command`] struct and their exit
  941. /// status is exposed through the [`status`] method.
  942. ///
  943. /// [`Command`]: struct.Command.html
  944. /// [`status`]: struct.Command.html#method.status
  945. #[derive(PartialEq, Eq, Clone, Copy, Debug)]
  946. #[stable(feature = "process", since = "1.0.0")]
  947. pub struct ExitStatus(imp::ExitStatus);
  948. impl ExitStatus {
  949. /// Was termination successful? Signal termination is not considered a
  950. /// success, and success is defined as a zero exit status.
  951. ///
  952. /// # Examples
  953. ///
  954. /// ```rust,no_run
  955. /// use std::process::Command;
  956. ///
  957. /// let status = Command::new("mkdir")
  958. /// .arg("projects")
  959. /// .status()
  960. /// .expect("failed to execute mkdir");
  961. ///
  962. /// if status.success() {
  963. /// println!("'projects/' directory created");
  964. /// } else {
  965. /// println!("failed to create 'projects/' directory");
  966. /// }
  967. /// ```
  968. #[stable(feature = "process", since = "1.0.0")]
  969. pub fn success(&self) -> bool {
  970. self.0.success()
  971. }
  972. /// Returns the exit code of the process, if any.
  973. ///
  974. /// On Unix, this will return `None` if the process was terminated
  975. /// by a signal; `std::os::unix` provides an extension trait for
  976. /// extracting the signal and other details from the `ExitStatus`.
  977. ///
  978. /// # Examples
  979. ///
  980. /// ```no_run
  981. /// use std::process::Command;
  982. ///
  983. /// let status = Command::new("mkdir")
  984. /// .arg("projects")
  985. /// .status()
  986. /// .expect("failed to execute mkdir");
  987. ///
  988. /// match status.code() {
  989. /// Some(code) => println!("Exited with status code: {}", code),
  990. /// None => println!("Process terminated by signal")
  991. /// }
  992. /// ```
  993. #[stable(feature = "process", since = "1.0.0")]
  994. pub fn code(&self) -> Option<i32> {
  995. self.0.code()
  996. }
  997. }
  998. impl AsInner<imp::ExitStatus> for ExitStatus {
  999. fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
  1000. }
  1001. impl FromInner<imp::ExitStatus> for ExitStatus {
  1002. fn from_inner(s: imp::ExitStatus) -> ExitStatus {
  1003. ExitStatus(s)
  1004. }
  1005. }
  1006. #[stable(feature = "process", since = "1.0.0")]
  1007. impl fmt::Display for ExitStatus {
  1008. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1009. self.0.fmt(f)
  1010. }
  1011. }
  1012. /// This type represents the status code a process can return to its
  1013. /// parent under normal termination.
  1014. ///
  1015. /// Numeric values used in this type don't have portable meanings, and
  1016. /// different platforms may mask different amounts of them.
  1017. ///
  1018. /// For the platform's canonical successful and unsuccessful codes, see
  1019. /// the [`SUCCESS`] and [`FAILURE`] associated items.
  1020. ///
  1021. /// [`SUCCESS`]: #associatedconstant.SUCCESS
  1022. /// [`FAILURE`]: #associatedconstant.FAILURE
  1023. ///
  1024. /// **Warning**: While various forms of this were discussed in [RFC #1937],
  1025. /// it was ultimately cut from that RFC, and thus this type is more subject
  1026. /// to change even than the usual unstable item churn.
  1027. ///
  1028. /// [RFC #1937]: https://github.com/rust-lang/rfcs/pull/1937
  1029. #[derive(Clone, Copy, Debug)]
  1030. #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
  1031. pub struct ExitCode(imp::ExitCode);
  1032. #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
  1033. impl ExitCode {
  1034. /// The canonical ExitCode for successful termination on this platform.
  1035. ///
  1036. /// Note that a `()`-returning `main` implicitly results in a successful
  1037. /// termination, so there's no need to return this from `main` unless
  1038. /// you're also returning other possible codes.
  1039. #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
  1040. pub const SUCCESS: ExitCode = ExitCode(imp::ExitCode::SUCCESS);
  1041. /// The canonical ExitCode for unsuccessful termination on this platform.
  1042. ///
  1043. /// If you're only returning this and `SUCCESS` from `main`, consider
  1044. /// instead returning `Err(_)` and `Ok(())` respectively, which will
  1045. /// return the same codes (but will also `eprintln!` the error).
  1046. #[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
  1047. pub const FAILURE: ExitCode = ExitCode(imp::ExitCode::FAILURE);
  1048. }
  1049. impl Child {
  1050. /// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
  1051. /// error is returned.
  1052. ///
  1053. /// The mapping to [`ErrorKind`]s is not part of the compatibility contract of the function,
  1054. /// especially the [`Other`] kind might change to more specific kinds in the future.
  1055. ///
  1056. /// This is equivalent to sending a SIGKILL on Unix platforms.
  1057. ///
  1058. /// # Examples
  1059. ///
  1060. /// Basic usage:
  1061. ///
  1062. /// ```no_run
  1063. /// use std::process::Command;
  1064. ///
  1065. /// let mut command = Command::new("yes");
  1066. /// if let Ok(mut child) = command.spawn() {
  1067. /// child.kill().expect("command wasn't running");
  1068. /// } else {
  1069. /// println!("yes command didn't start");
  1070. /// }
  1071. /// ```
  1072. ///
  1073. /// [`ErrorKind`]: ../io/enum.ErrorKind.html
  1074. /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
  1075. /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
  1076. #[stable(feature = "process", since = "1.0.0")]
  1077. pub fn kill(&mut self) -> io::Result<()> {
  1078. self.handle.kill()
  1079. }
  1080. /// Returns the OS-assigned process identifier associated with this child.
  1081. ///
  1082. /// # Examples
  1083. ///
  1084. /// Basic usage:
  1085. ///
  1086. /// ```no_run
  1087. /// use std::process::Command;
  1088. ///
  1089. /// let mut command = Command::new("ls");
  1090. /// if let Ok(child) = command.spawn() {
  1091. /// println!("Child's id is {}", child.id());
  1092. /// } else {
  1093. /// println!("ls command didn't start");
  1094. /// }
  1095. /// ```
  1096. #[stable(feature = "process_id", since = "1.3.0")]
  1097. pub fn id(&self) -> u32 {
  1098. self.handle.id()
  1099. }
  1100. /// Waits for the child to exit completely, returning the status that it
  1101. /// exited with. This function will continue to have the same return value
  1102. /// after it has been called at least once.
  1103. ///
  1104. /// The stdin handle to the child process, if any, will be closed
  1105. /// before waiting. This helps avoid deadlock: it ensures that the
  1106. /// child does not block waiting for input from the parent, while
  1107. /// the parent waits for the child to exit.
  1108. ///
  1109. /// # Examples
  1110. ///
  1111. /// Basic usage:
  1112. ///
  1113. /// ```no_run
  1114. /// use std::process::Command;
  1115. ///
  1116. /// let mut command = Command::new("ls");
  1117. /// if let Ok(mut child) = command.spawn() {
  1118. /// child.wait().expect("command wasn't running");
  1119. /// println!("Child has finished its execution!");
  1120. /// } else {
  1121. /// println!("ls command didn't start");
  1122. /// }
  1123. /// ```
  1124. #[stable(feature = "process", since = "1.0.0")]
  1125. pub fn wait(&mut self) -> io::Result<ExitStatus> {
  1126. drop(self.stdin.take());
  1127. self.handle.wait().map(ExitStatus)
  1128. }
  1129. /// Attempts to collect the exit status of the child if it has already
  1130. /// exited.
  1131. ///
  1132. /// This function will not block the calling thread and will only advisorily
  1133. /// check to see if the child process has exited or not. If the child has
  1134. /// exited then on Unix the process id is reaped. This function is
  1135. /// guaranteed to repeatedly return a successful exit status so long as the
  1136. /// child has already exited.
  1137. ///
  1138. /// If the child has exited, then `Ok(Some(status))` is returned. If the
  1139. /// exit status is not available at this time then `Ok(None)` is returned.
  1140. /// If an error occurs, then that error is returned.
  1141. ///
  1142. /// Note that unlike `wait`, this function will not attempt to drop stdin.
  1143. ///
  1144. /// # Examples
  1145. ///
  1146. /// Basic usage:
  1147. ///
  1148. /// ```no_run
  1149. /// use std::process::Command;
  1150. ///
  1151. /// let mut child = Command::new("ls").spawn().unwrap();
  1152. ///
  1153. /// match child.try_wait() {
  1154. /// Ok(Some(status)) => println!("exited with: {}", status),
  1155. /// Ok(None) => {
  1156. /// println!("status not ready yet, let's really wait");
  1157. /// let res = child.wait();
  1158. /// println!("result: {:?}", res);
  1159. /// }
  1160. /// Err(e) => println!("error attempting to wait: {}", e),
  1161. /// }
  1162. /// ```
  1163. #[stable(feature = "process_try_wait", since = "1.18.0")]
  1164. pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
  1165. Ok(self.handle.try_wait()?.map(ExitStatus))
  1166. }
  1167. /// Simultaneously waits for the child to exit and collect all remaining
  1168. /// output on the stdout/stderr handles, returning an `Output`
  1169. /// instance.
  1170. ///
  1171. /// The stdin handle to the child process, if any, will be closed
  1172. /// before waiting. This helps avoid deadlock: it ensures that the
  1173. /// child does not block waiting for input from the parent, while
  1174. /// the parent waits for the child to exit.
  1175. ///
  1176. /// By default, stdin, stdout and stderr are inherited from the parent.
  1177. /// In order to capture the output into this `Result<Output>` it is
  1178. /// necessary to create new pipes between parent and child. Use
  1179. /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
  1180. ///
  1181. /// # Examples
  1182. ///
  1183. /// ```should_panic
  1184. /// use std::process::{Command, Stdio};
  1185. ///
  1186. /// let child = Command::new("/bin/cat")
  1187. /// .arg("file.txt")
  1188. /// .stdout(Stdio::piped())
  1189. /// .spawn()
  1190. /// .expect("failed to execute child");
  1191. ///
  1192. /// let output = child
  1193. /// .wait_with_output()
  1194. /// .expect("failed to wait on child");
  1195. ///
  1196. /// assert!(output.status.success());
  1197. /// ```
  1198. ///
  1199. #[stable(feature = "process", since = "1.0.0")]
  1200. pub fn wait_with_output(mut self) -> io::Result<Output> {
  1201. drop(self.stdin.take());
  1202. let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
  1203. match (self.stdout.take(), self.stderr.take()) {
  1204. (None, None) => {}
  1205. (Some(mut out), None) => {
  1206. let res = out.read_to_end(&mut stdout);
  1207. res.unwrap();
  1208. }
  1209. (None, Some(mut err)) => {
  1210. let res = err.read_to_end(&mut stderr);
  1211. res.unwrap();
  1212. }
  1213. (Some(out), Some(err)) => {
  1214. let res = read2(out.inner, &mut stdout, err.inner, &mut stderr);
  1215. res.unwrap();
  1216. }
  1217. }
  1218. let status = self.wait()?;
  1219. Ok(Output {
  1220. status,
  1221. stdout,
  1222. stderr,
  1223. })
  1224. }
  1225. }
  1226. /// Terminates the current process with the specified exit code.
  1227. ///
  1228. /// This function will never return and will immediately terminate the current
  1229. /// process. The exit code is passed through to the underlying OS and will be
  1230. /// available for consumption by another process.
  1231. ///
  1232. /// Note that because this function never returns, and that it terminates the
  1233. /// process, no destructors on the current stack or any other thread's stack
  1234. /// will be run. If a clean shutdown is needed it is recommended to only call
  1235. /// this function at a known point where there are no more destructors left
  1236. /// to run.
  1237. ///
  1238. /// ## Platform-specific behavior
  1239. ///
  1240. /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit`
  1241. /// will be visible to a parent process inspecting the exit code. On most
  1242. /// Unix-like platforms, only the eight least-significant bits are considered.
  1243. ///
  1244. /// # Examples
  1245. ///
  1246. /// Due to this function’s behavior regarding destructors, a conventional way
  1247. /// to use the function is to extract the actual computation to another
  1248. /// function and compute the exit code from its return value:
  1249. ///
  1250. /// ```
  1251. /// fn run_app() -> Result<(), ()> {
  1252. /// // Application logic here
  1253. /// Ok(())
  1254. /// }
  1255. ///
  1256. /// fn main() {
  1257. /// ::std::process::exit(match run_app() {
  1258. /// Ok(_) => 0,
  1259. /// Err(err) => {
  1260. /// eprintln!("error: {:?}", err);
  1261. /// 1
  1262. /// }
  1263. /// });
  1264. /// }
  1265. /// ```
  1266. ///
  1267. /// Due to [platform-specific behavior], the exit code for this example will be
  1268. /// `0` on Linux, but `256` on Windows:
  1269. ///
  1270. /// ```no_run
  1271. /// use std::process;
  1272. ///
  1273. /// process::exit(0x0100);
  1274. /// ```
  1275. ///
  1276. /// [platform-specific behavior]: #platform-specific-behavior
  1277. #[stable(feature = "rust1", since = "1.0.0")]
  1278. pub fn exit(code: i32) -> ! {
  1279. ::sys_common::cleanup();
  1280. ::sys::os::exit(code)
  1281. }
  1282. /// Terminates the process in an abnormal fashion.
  1283. ///
  1284. /// The function will never return and will immediately terminate the current
  1285. /// process in a platform specific "abnormal" manner.
  1286. ///
  1287. /// Note that because this function never returns, and that it terminates the
  1288. /// process, no destructors on the current stack or any other thread's stack
  1289. /// will be run.
  1290. ///
  1291. /// This is in contrast to the default behaviour of [`panic!`] which unwinds
  1292. /// the current thread's stack and calls all destructors.
  1293. /// When `panic="abort"` is set, either as an argument to `rustc` or in a
  1294. /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However,
  1295. /// [`panic!`] will still call the [panic hook] while `abort` will not.
  1296. ///
  1297. /// If a clean shutdown is needed it is recommended to only call
  1298. /// this function at a known point where there are no more destructors left
  1299. /// to run.
  1300. ///
  1301. /// # Examples
  1302. ///
  1303. /// ```no_run
  1304. /// use std::process;
  1305. ///
  1306. /// fn main() {
  1307. /// println!("aborting");
  1308. ///
  1309. /// process::abort();
  1310. ///
  1311. /// // execution never gets here
  1312. /// }
  1313. /// ```
  1314. ///
  1315. /// The `abort` function terminates the process, so the destructor will not
  1316. /// get run on the example below:
  1317. ///
  1318. /// ```no_run
  1319. /// use std::process;
  1320. ///
  1321. /// struct HasDrop;
  1322. ///
  1323. /// impl Drop for HasDrop {
  1324. /// fn drop(&mut self) {
  1325. /// println!("This will never be printed!");
  1326. /// }
  1327. /// }
  1328. ///
  1329. /// fn main() {
  1330. /// let _x = HasDrop;
  1331. /// process::abort();
  1332. /// // the destructor implemented for HasDrop will never get run
  1333. /// }
  1334. /// ```
  1335. ///
  1336. /// [`panic!`]: ../../std/macro.panic.html
  1337. /// [panic hook]: ../../std/panic/fn.set_hook.html
  1338. #[stable(feature = "process_abort", since = "1.17.0")]
  1339. pub fn abort() -> ! {
  1340. unsafe { ::sys::abort_internal() };
  1341. }
  1342. /// Returns the OS-assigned process identifier associated with this process.
  1343. ///
  1344. /// # Examples
  1345. ///
  1346. /// Basic usage:
  1347. ///
  1348. /// ```no_run
  1349. /// use std::process;
  1350. ///
  1351. /// println!("My pid is {}", process::id());
  1352. /// ```
  1353. ///
  1354. ///
  1355. #[stable(feature = "getpid", since = "1.26.0")]
  1356. pub fn id() -> u32 {
  1357. ::sys::os::getpid()
  1358. }
  1359. /// A trait for implementing arbitrary return types in the `main` function.
  1360. ///
  1361. /// The c-main function only supports to return integers as return type.
  1362. /// So, every type implementing the `Termination` trait has to be converted
  1363. /// to an integer.
  1364. ///
  1365. /// The default implementations are returning `libc::EXIT_SUCCESS` to indicate
  1366. /// a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.
  1367. #[cfg_attr(not(test), lang = "termination")]
  1368. #[unstable(feature = "termination_trait_lib", issue = "43301")]
  1369. #[rustc_on_unimplemented(
  1370. message="`main` has invalid return type `{Self}`",
  1371. label="`main` can only return types that implement `{Termination}`")]
  1372. pub trait Termination {
  1373. /// Is called to get the representation of the value as status code.
  1374. /// This status code is returned to the operating system.
  1375. fn report(self) -> i32;
  1376. }
  1377. #[unstable(feature = "termination_trait_lib", issue = "43301")]
  1378. impl Termination for () {
  1379. #[inline]
  1380. fn report(self) -> i32 { ExitCode::SUCCESS.report() }
  1381. }
  1382. #[unstable(feature = "termination_trait_lib", issue = "43301")]
  1383. impl<E: fmt::Debug> Termination for Result<(), E> {
  1384. fn report(self) -> i32 {
  1385. match self {
  1386. Ok(()) => ().report(),
  1387. Err(err) => Err::<!, _>(err).report(),
  1388. }
  1389. }
  1390. }
  1391. #[unstable(feature = "termination_trait_lib", issue = "43301")]
  1392. impl Termination for ! {
  1393. fn report(self) -> i32 { self }
  1394. }
  1395. #[unstable(feature = "termination_trait_lib", issue = "43301")]
  1396. impl<E: fmt::Debug> Termination for Result<!, E> {
  1397. fn report(self) -> i32 {
  1398. let Err(err) = self;
  1399. eprintln!("Error: {:?}", err);
  1400. ExitCode::FAILURE.report()
  1401. }
  1402. }
  1403. #[unstable(feature = "termination_trait_lib", issue = "43301")]
  1404. impl Termination for ExitCode {
  1405. #[inline]
  1406. fn report(self) -> i32 {
  1407. self.0.as_i32()
  1408. }
  1409. }
  1410. #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
  1411. mod tests {
  1412. use io::prelude::*;
  1413. use io::ErrorKind;
  1414. use str;
  1415. use super::{Command, Output, Stdio};
  1416. // FIXME(#10380) these tests should not all be ignored on android.
  1417. #[test]
  1418. #[cfg_attr(target_os = "android", ignore)]
  1419. fn smoke() {
  1420. let p = if cfg!(target_os = "windows") {
  1421. Command::new("cmd").args(&["/C", "exit 0"]).spawn()
  1422. } else {
  1423. Command::new("true").spawn()
  1424. };
  1425. assert!(p.is_ok());
  1426. let mut p = p.unwrap();
  1427. assert!(p.wait().unwrap().success());
  1428. }
  1429. #[test]
  1430. #[cfg_attr(target_os = "android", ignore)]
  1431. fn smoke_failure() {
  1432. match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
  1433. Ok(..) => panic!(),
  1434. Err(..) => {}
  1435. }
  1436. }
  1437. #[test]
  1438. #[cfg_attr(target_os = "android", ignore)]
  1439. fn exit_reported_right() {
  1440. let p = if cfg!(target_os = "windows") {
  1441. Command::new("cmd").args(&["/C", "exit 1"]).spawn()
  1442. } else {
  1443. Command::new("false").spawn()
  1444. };
  1445. assert!(p.is_ok());
  1446. let mut p = p.unwrap();
  1447. assert!(p.wait().unwrap().code() == Some(1));
  1448. drop(p.wait());
  1449. }
  1450. #[test]
  1451. #[cfg(unix)]
  1452. #[cfg_attr(target_os = "android", ignore)]
  1453. fn signal_reported_right() {
  1454. use os::unix::process::ExitStatusExt;
  1455. let mut p = Command::new("/bin/sh")
  1456. .arg("-c").arg("read a")
  1457. .stdin(Stdio::piped())
  1458. .spawn().unwrap();
  1459. p.kill().unwrap();
  1460. match p.wait().unwrap().signal() {
  1461. Some(9) => {},
  1462. result => panic!("not terminated by signal 9 (instead, {:?})",
  1463. result),
  1464. }
  1465. }
  1466. pub fn run_output(mut cmd: Command) -> String {
  1467. let p = cmd.spawn();
  1468. assert!(p.is_ok());
  1469. let mut p = p.unwrap();
  1470. assert!(p.stdout.is_some());
  1471. let mut ret = String::new();
  1472. p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
  1473. assert!(p.wait().unwrap().success());
  1474. return ret;
  1475. }
  1476. #[test]
  1477. #[cfg_attr(target_os = "android", ignore)]
  1478. fn stdout_works() {
  1479. if cfg!(target_os = "windows") {
  1480. let mut cmd = Command::new("cmd");
  1481. cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
  1482. assert_eq!(run_output(cmd), "foobar\r\n");
  1483. } else {
  1484. let mut cmd = Command::new("echo");
  1485. cmd.arg("foobar").stdout(Stdio::piped());
  1486. assert_eq!(run_output(cmd), "foobar\n");
  1487. }
  1488. }
  1489. #[test]
  1490. #[cfg_attr(any(windows, target_os = "android"), ignore)]
  1491. fn set_current_dir_works() {
  1492. let mut cmd = Command::new("/bin/sh");
  1493. cmd.arg("-c").arg("pwd")
  1494. .current_dir("/")
  1495. .stdout(Stdio::piped());
  1496. assert_eq!(run_output(cmd), "/\n");
  1497. }
  1498. #[test]
  1499. #[cfg_attr(any(windows