Skip to content
systemcoding.dev
Systems Programming

Fork and Exec Safely in Rust with CommandExt::pre_exec

Run code in the child between fork and exec with CommandExt::pre_exec, learn which calls are async-signal-safe, and see how errors propagate to spawn.

6 min read
Summarize in AI
Flat illustration of a terminal session, with the Rust, Linux and GNU Bash logos.

Most of the time std::process::Command is all you need to start a program. Sometimes you must change something about the child before it runs: its umask, its resource limits, its session, which descriptors it keeps. In C you do that in the gap between fork and exec. Rust gives you the same gap through one method, CommandExt::pre_exec, and it is unsafe for a reason you need to understand before you use it.

The examples use Rust 1.85 on Linux 6.12 with glibc 2.41 and the libc crate 0.2. pre_exec is documented in [std::os::unix::process::CommandExt](https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html).

What pre_exec does

pre_exec registers a closure that runs in the child process after fork and before exec. The signature is:

Text
unsafe fn pre_exec<F>(&mut self, f: F) -> &mut Command
where F: FnMut() -> io::Result<()> + Send + Sync + 'static

If the closure returns an error, exec never happens. The error travels back to the parent through a pipe that std sets up for this purpose, and spawn returns it as an Err. So a failed setup step in the child shows up as a normal io::Error at the call site, which is much easier than C, where the child just exits with some status.

Registering a pre_exec closure has one side effect worth knowing. By default, std can start a process with posix_spawn on Linux, which avoids a full fork. A pre_exec hook forces the classic fork and exec path, because posix_spawn has no place to run arbitrary code.

A first example: set the umask

The umask is inherited by the child and is the standard example of "something you set before exec". The shell builtin umask prints it, so the result is easy to check.

umask.rsrust
use std::io;
use std::os::unix::process::CommandExt;
use std::process::Command;

fn main() -> io::Result<()> {
    let mut cmd = Command::new("sh");
    cmd.arg("-c").arg("umask");

    unsafe {
        cmd.pre_exec(|| {
            libc::umask(0o077);
            Ok(())
        });
    }

    let output = cmd.output()?;
    print!("{}", String::from_utf8_lossy(&output.stdout));
    Ok(())
}
Text
0077

The parent's own umask is unchanged, because the call ran in the child. libc::umask cannot fail, so the closure always returns Ok(()). Note the unsafe block: calling pre_exec is unsafe because the closure runs in a state the compiler cannot reason about.

Why it is unsafe

After fork, the child is a copy of the parent with exactly one thread, the one that called fork. Every other thread vanishes, along with whatever it was doing. If one of those threads held a lock, say the memory allocator's lock, the child inherits a locked lock that nobody will ever release. The moment the closure allocates, it deadlocks.

POSIX therefore says that after fork in a multithreaded program, the child may call only async-signal-safe functions until it calls exec. The list is in signal-safety(7). It includes umask, setsid, setpgid, dup2, close, setrlimit, chdir and write. It does not include malloc, printf or anything in Rust that allocates, such as format!, String::push_str or Vec::push. A Rust closure also must not panic, since the panic machinery allocates.

The practical rules for the closure body:

  • Call libc functions directly, not wrappers that allocate.

  • Do not print, format or log.

  • Do not take a Mutex, and do not touch thread-local data that might lazily allocate.

  • Create any error value you return from a pre-built io::Error::from_raw_os_error, which does not allocate.

A realistic use: a new session and a limit

Running a daemon-like helper usually means detaching it from the parent's terminal and capping its resources. Both are one-line system calls.

detach.rsrust
use std::io;
use std::os::unix::process::CommandExt;
use std::process::Command;

fn main() -> io::Result<()> {
    let mut cmd = Command::new("sh");
    cmd.arg("-c").arg("ulimit -n");

    unsafe {
        cmd.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(io::Error::last_os_error());
            }
            let limit = libc::rlimit { rlim_cur: 64, rlim_max: 64 };
            if libc::setrlimit(libc::RLIMIT_NOFILE, &limit) == -1 {
                return Err(io::Error::last_os_error());
            }
            Ok(())
        });
    }

    let output = cmd.output()?;
    print!("{}", String::from_utf8_lossy(&output.stdout));
    Ok(())
}
Text
64

setsid creates a new session with no controlling terminal, so a Ctrl-C in the parent's terminal no longer reaches the child. setrlimit lowers the open-file limit to 64 for the child only, and ulimit -n in the shell reports it. io::Error::last_os_error() reads errno and builds an error from the code without allocating, so it is safe in this context. Lowering a limit never needs privilege, but raising a hard limit does.

If you only want a new process group, you do not need pre_exec at all. CommandExt::process_group(0) is stable since Rust 1.64 and is a safe method. Prefer the safe builders when they exist: uid, gid, groups, arg0 and process_group cover the common cases.

Errors flow back to spawn

Make the closure fail on purpose and watch what spawn reports.

failing.rsrust
use std::io;
use std::os::unix::process::CommandExt;
use std::process::Command;

fn main() {
    let mut cmd = Command::new("true");
    unsafe {
        cmd.pre_exec(|| Err(io::Error::from_raw_os_error(libc::EPERM)));
    }
    match cmd.spawn() {
        Ok(_) => println!("started"),
        Err(e) => println!("spawn failed: {e}"),
    }
}
Text
spawn failed: Operation not permitted (os error 1)

The program true never ran. The error code made the round trip through the pipe, and std rebuilt an io::Error from the raw errno. Only OS errors survive this trip, which is another reason to build errors with from_raw_os_error: an io::Error::new(ErrorKind::Other, "text") carries a heap-allocated message that cannot cross the pipe, and std reports a generic failure instead.

Closing descriptors you do not want to inherit

Rust opens its own files with O_CLOEXEC, so they vanish at exec on their own. Descriptors you got from elsewhere, for example from C code, may not have the flag. A pre_exec closure that calls libc::close on specific numbers is the classic fix, though setting FD_CLOEXEC at creation time is cleaner. Kernels since 5.9 also provide close_range(2), which closes a range in one call and is async-signal-safe.

Pitfalls

**Do not use pre_exec for work that can be done before the fork.** Open files, resolve paths and build strings in the parent, then move the results into the closure. The closure then only makes system calls.

The closure runs once per spawn, in each child. Capturing a Vec and mutating it is allowed by the types and a mistake in practice, because a push may allocate.

Do not rely on it being portable. The trait lives under std::os::unix, so it is absent on Windows. Hide the code behind cfg(unix).

**Mind vfork.** Some std paths may use posix_spawn or vfork-like behavior on newer releases when no pre_exec is present. With the hook, std takes the fork path, so memory changes in the closure do not affect the parent. Do not write code that depends on either.

When not to use it

If a safe method exists, use it. If you need to run substantial logic before exec, do it in a tiny helper program that you spawn, and keep pre_exec for a handful of raw system calls. And if your program is single-threaded and you are certain of it, the deadlock risk is gone, but a later change that adds a thread will bring it back silently.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.