Skip to content

Commit 001bfb9

Browse files
authored
Rollup merge of rust-lang#38518 - nagisa:exec-doc, r=alexcrichton
Expand documentation of process::exit and exec Show a conventional way to use process::exit when destructors are considered important and also mention that the same caveats wrt destructors apply to exec as well.
2 parents 696f5c1 + c2eab73 commit 001bfb9

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/libstd/process.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -959,10 +959,27 @@ impl Child {
959959
///
960960
/// # Examples
961961
///
962+
/// Due to this function’s behavior regarding destructors, a conventional way
963+
/// to use the function is to extract the actual computation to another
964+
/// function and compute the exit code from its return value:
965+
///
962966
/// ```
963-
/// use std::process;
967+
/// use std::io::{self, Write};
968+
///
969+
/// fn run_app() -> Result<(), ()> {
970+
/// // Application logic here
971+
/// Ok(())
972+
/// }
964973
///
965-
/// process::exit(0);
974+
/// fn main() {
975+
/// ::std::process::exit(match run_app() {
976+
/// Ok(_) => 0,
977+
/// Err(err) => {
978+
/// writeln!(io::stderr(), "error: {:?}", err).unwrap();
979+
/// 1
980+
/// }
981+
/// });
982+
/// }
966983
/// ```
967984
///
968985
/// Due to [platform-specific behavior], the exit code for this example will be

src/libstd/sys/unix/ext/process.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,20 @@ pub trait CommandExt {
6767
/// an error indicating why the exec (or another part of the setup of the
6868
/// `Command`) failed.
6969
///
70+
/// `exec` not returning has the same implications as calling
71+
/// [`process::exit`] – no destructors on the current stack or any other
72+
/// thread’s stack will be run. Therefore, it is recommended to only call
73+
/// `exec` at a point where it is fine to not run any destructors. Note,
74+
/// that the `execvp` syscall independently guarantees that all memory is
75+
/// freed and all file descriptors with the `CLOEXEC` option (set by default
76+
/// on all file descriptors opened by the standard library) are closed.
77+
///
7078
/// This function, unlike `spawn`, will **not** `fork` the process to create
7179
/// a new child. Like spawn, however, the default behavior for the stdio
7280
/// descriptors will be to inherited from the current process.
7381
///
82+
/// [`process::exit`]: ../../../process/fn.exit.html
83+
///
7484
/// # Notes
7585
///
7686
/// The process may be in a "broken state" if this function returns in

0 commit comments

Comments
 (0)