Skip to content

Commit c2eab73

Browse files
committed
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.
1 parent 3dcb288 commit c2eab73

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/libstd/process.rs

+19-2
Original file line numberDiff line numberDiff line change
@@ -924,10 +924,27 @@ impl Child {
924924
///
925925
/// # Examples
926926
///
927+
/// Due to this function’s behavior regarding destructors, a conventional way
928+
/// to use the function is to extract the actual computation to another
929+
/// function and compute the exit code from its return value:
930+
///
927931
/// ```
928-
/// use std::process;
932+
/// use std::io::{self, Write};
933+
///
934+
/// fn run_app() -> Result<(), ()> {
935+
/// // Application logic here
936+
/// Ok(())
937+
/// }
929938
///
930-
/// process::exit(0);
939+
/// fn main() {
940+
/// ::std::process::exit(match run_app() {
941+
/// Ok(_) => 0,
942+
/// Err(err) => {
943+
/// writeln!(io::stderr(), "error: {:?}", err).unwrap();
944+
/// 1
945+
/// }
946+
/// });
947+
/// }
931948
/// ```
932949
///
933950
/// Due to [platform-specific behavior], the exit code for this example will be

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

+10
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)