Module 9 · Lesson 51 of 112

nix fork, exec, and file descriptors

Use nix to follow fork and exec, manage descriptor ownership, and measure how buffering changes the syscall count of a byte-copy tool.

  • Beginner to advanced
  • 10 min read
  • 36 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, a Rust toolchain with edition 2024 support, Cargo, nix 0.30.1, and strace

Your place in the module
By the end you can 4 objectives
  • Distinguish a program's exit code from the termination status its parent observes.
  • Trace process identity and descriptor inheritance through fork and execve.
  • Use owned descriptors to open, duplicate, read, write, and close Linux I/O resources.
  • Compare buffered and raw byte-copy implementations with strace.
Video coming soonnix fork, exec, and file descriptors
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Files, paths, and processes
  • Path operations such as join and extension inspect or construct names without accessing the filesystem.
  • Whole-file reads allocate for the entire input, while buffered readers can process it incrementally.
  • Command passes arguments directly and exposes a separate exit status for a program that ran.
01

Process state, fork, and exec

5 min read

You used std to run commands and read files. This lesson answers how the nix crate exposes fork, exec, and file descriptors safely.

When a shell runs printf '%s\n' ready > status.txt, printf writes to standard output and the bytes end up in a file. An external program can use the same convention. Before starting it, the launcher arranges for descriptor 1 to refer to the requested destination. execve preserves open descriptors unless they are marked close-on-exec. That rule explains why the replacement program can write to the file without receiving its name as an argument. execve(2)

The nix crate provides Rust bindings for Unix operations. Many APIs are safe to call and express their inputs and results as Rust types. Some operations, including fork, require an explicit unsafe call. The snippets here use nix = { version = "=0.30.1", features = ["fs", "process", "user"] } in Cargo.toml. The version matters because descriptor APIs in older examples can have different signatures.

A process has arguments, environment variables, and a working directory. std::env::args() iterates over arguments as String values. The first entry conventionally identifies the program. Use args_os() when an argument can contain bytes that are invalid UTF-8, as a Linux filename can. std::env::vars() gives a snapshot of the environment as string pairs. Use vars_os() to preserve non-Unicode names and values. std::env::current_dir() returns a Result<PathBuf> for the working directory used to resolve relative paths. nix::unistd::chdir changes that directory for the whole process. A child inherits the directory at fork, and it remains the working directory across execve.

std::env::set_var changes the current process's environment. It is unsafe to call in edition 2024. On Linux, other threads or libraries can access the environment outside Rust's own synchronization. If you only need to configure a subprocess, use Command::env. With execve, supply the environment explicitly as a slice of C strings such as c"LANG=C". An empty slice gives the new program an empty environment.

nix::unistd::getpid() reports the calling process's ID, and getppid() reports its current parent's ID. getuid() reports the real user ID, while geteuid() reports the effective user ID, which participates in permission checks. setuid(uid) asks the kernel to change credentials. It returns a result you must check. The process's privileges and existing IDs determine which changes the kernel allows. You can inspect both IDs from an ordinary account without trying to change them.

unsafe { nix::unistd::fork() } returns a Result<ForkResult>. On success, the parent gets ForkResult::Parent { child } with the child's PID, and the child gets ForkResult::Child. Both resume just after the call, and either can run first. A failed call returns an error in the original process and creates no child. The processes have separate memory, but inherited descriptors refer to the same underlying open file descriptions. For a regular file, that can mean a shared offset. fork(2)

The child can use nix::unistd::execve(c"/usr/bin/true", &[c"true"], &[c"LANG=C"]) to load a program. The first argument names the executable directly, so this call does no PATH search. The second supplies the argument vector, including the conventional program name at index zero. The third supplies the environment. Prepare these inputs before fork. Successful execve never returns. If it returns an error, the child must take a failure path, because it is still executing the original program. A parent that starts a child directly should collect its termination status with nix::sys::wait::waitpid(child, None). Retry the wait if interrupted by EINTR. execve(2)

Process identity through fork and execCall forkParent getschild PIDChild getsits ownreturnvalueChild callsexecveReplacementprogramSame childPIDExit from step 3: execve failsError in childCall forkParent getschild PIDChild getsits ownreturnvalueChild callsexecveReplacementprogramSame childPIDExit from step 3: execvefailsError in child
Fork creates a second process. Execve replaces the program inside the calling child.
Going deeperExplore the mechanism

In a multithreaded process, only the calling thread survives in the child after fork. The child still inherits memory containing locks that other threads may have held. A print, allocation, or destructor in the child can attempt to acquire one of those locks and wait indefinitely. Between fork and execve in that child, restrict the code to async-signal-safe operations. In particular, an execve failure path should terminate with _exit, for example via nix::libc::_exit in an unsafe block, without running Rust cleanup or formatting an error. Prepare paths, arguments, and environment before the call. Prefer std::process::Command for ordinary subprocesses, or posix_spawn when using a POSIX interface that supports the setup you need. fork(2)

Your program can return std::process::ExitCode from main. ExitCode::SUCCESS and ExitCode::FAILURE cover the common cases, and ExitCode::from(2) lets a command publish a specific code. std::process::exit(2) terminates immediately without running Rust destructors on the stacks. Explicitly flush buffered output and check the result before terminating. Returning from main lets its locals drop normally, but even then an explicit flush is needed if you want to report a flush failure.

A parent using Command::status() receives an ExitStatus when the command runs and a status is collected. Use status.success() to check successful termination and status.code() to get Some(code) for normal exit. On Linux, termination by a signal gives None from code(). The shell and other waiting programs see only the low eight bits of a normal exit value, so choose a code in 0..=255. ExitCode is what your program supplies, while ExitStatus is what its parent observes.

02

Descriptor numbers and ownership

3 min read

A can refer to a regular file, a terminal, or one end of a pipe. Programs conventionally use descriptor 0 for standard input, 1 for standard output, and 2 for standard error. A call to nix::fcntl::open returns an OwnedFd on success. With the version in this lesson, the Rust names are nix::fcntl::open and nix::fcntl::OFlag (singular). close, dup, and dup2 live in nix::unistd.

Open an input with open(path, OFlag::O_RDONLY | OFlag::O_CLOEXEC, Mode::empty()). Mode comes from nix::sys::stat. When creating a new output file, OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC | OFlag::O_CLOEXEC requests writing, creation if absent, truncation if present, and closure on successful exec. Pass Mode::from_bits_truncate(0o644) as the requested creation mode. The process's umask can remove permission bits. For the byte-copy tool, open the input before opening the output and use a separate output file. Truncating an output that refers to the input file destroys the data before the loop can read it. open(2)

std::os::fd::RawFd is the integer type for the descriptor number. The AsRawFd trait exposes that number via .as_raw_fd() without transferring ownership or extending its lifetime. After the owner closes the descriptor, the kernel can reuse the number. For the nix I/O functions in this lesson, keep the owner alive and pass a reference such as &input. The AsFd interface lets the call borrow the descriptor.

FromRawFd::from_raw_fd goes in the other direction. For OwnedFd or File, it creates an owner from a raw number and is unsafe. Before calling it, you must have a valid open descriptor you can transfer to the new owner. Using a number obtained from another live owner's .as_raw_fd() would create two owners for one entry, and dropping either could close it while the other still expects it to be open. To turn an OwnedFd into a standard File, use File::from(fd) to move ownership safely.

Dropping an OwnedFd closes its entry. To close it explicitly and inspect the result, pass the owner by value to nix::unistd::close(fd). nix::unistd::dup(&fd) creates a new owned descriptor for the same open file description. Either owner can be closed independently. Reads from the two descriptors of a regular file advance the same offset. Opening the file twice gives two separate open file descriptions, each with its own offset. dup(2)

Two descriptors share one open file descriptionOpen file descriptionContains the shared offsetOriginal descriptorRefers to this descriptionDuplicate descriptorRefers to this descriptionOpen file descriptionContains the shared offsetOriginal descriptorRefers to this descriptionDuplicate descriptorRefers to this description
Both descriptors obtained through duplication refer to one open file description.

nix::unistd::dup2(&source, &mut destination) selects an existing owned destination descriptor in this version of the crate. It replaces the destination's binding atomically while keeping its number. This operation explains shell redirection: if the destination is descriptor 1, writes to standard output go where the source points. The source remains open. The destination's close-on-exec flag is cleared by a successful duplication between distinct descriptor numbers, so the redirected output can survive execve. Keep descriptor changes scoped to the process that needs them. dup(2)

nix::unistd::pipe() returns a pair of OwnedFd values in read-end, write-end order. You can send bytes into the write end and receive them from the read end. If the pipe is empty, a blocking read waits while any write descriptor remains open. Once all write descriptors are closed and the queued bytes have been read, the reader gets zero. After a fork, account for both processes' copies when deciding which ends to close.

03

Raw I/O and syscall counts

3 min read

A cat-style tool copies input bytes to standard output. A tee-style tool sends every chunk to standard output and to a file. In both cases, the copy loop must preserve the exact bytes it received, including a final chunk smaller than its buffer. Use blocking descriptors for this lesson. A successful nix::unistd::read(&input, &mut buf) returns the number of bytes available in the front of the buffer. For a regular file or pipe, zero with a nonempty buffer indicates end of input. A positive short read is valid data, so write those bytes and read again.

A call to nix::unistd::write may also succeed with a count smaller than the length supplied. Advance by the count it reports and keep writing from that position. For two destinations, complete the write loop for each destination using the same &buf[..n]. Advancing a slice for the first destination must leave the full chunk available to the second. If an operation returns Errno::EINTR, retry that call. Some bytes may already have been written during earlier successful calls. write(2)

rust
use nix::{errno::Errno, unistd::{read, write}};
use std::{io, os::fd::AsFd};

fn copy_raw(input: &impl AsFd, output: &impl AsFd) -> io::Result<()> {
    let mut buf = [0u8; 8192];
    loop {
        let n = match read(input, &mut buf) {
            Ok(0) => return Ok(()),
            Ok(n) => n,
            Err(Errno::EINTR) => continue,
            Err(e) => return Err(io::Error::from_raw_os_error(e as i32)),
        };
        let mut pending = &buf[..n];
        while !pending.is_empty() {
            match write(output, pending) {
                Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
                Ok(written) => pending = &pending[written..],
                Err(Errno::EINTR) => continue,
                Err(e) => return Err(io::Error::from_raw_os_error(e as i32)),
            }
        }
    }
}

Use an owned descriptor from open as the input and std::io::stdout() as the output. Keep stdout writes in this copy path. Mixing buffered prints with direct descriptor writes can change the order in which bytes appear. For the standard library version, wrap the input File in BufReader::with_capacity(8192, file) and the locked stdout handle in BufWriter::with_capacity(8192, stdout.lock()). Use Read::read into a small application buffer and Write::write_all on the slice returned by the read. Retry interrupted reads as in the raw loop, and call Write::flush at end of input. For tee, use a second BufWriter for the output file and check both flush results on the success path.

Copy one chunk at a timeRead intobufferUsereturnedbytesWriteentirechunkRetryunwrittenbytesExit from step 1: Zero bytesFinish copy↻ Repeat from step 1Read intobufferUsereturnedbytesExit from step 1: Zero bytesFinish copyWriteentirechunkRetryunwrittenbytes↻ Repeat from step 1
Write each returned chunk completely before reading again. A zero-byte read ends the copy.

To measure syscall counts, compare raw copies with different buffer sizes and a buffered copy that uses small application chunks. Use identical input and destinations in each run. With a binary named bytecopy that accepts a mode and input filename, the commands below create a binary fixture and trace the already-built program. The raw mode uses the 8192-byte buffer in the snippet. The buffered mode uses the same capacity for its wrappers and a smaller buffer in its application loop.

bash
dd if=/dev/zero of=copy-input.bin bs=1M count=1 status=none
strace -c -e trace=read,write,writev ./target/release/bytecopy raw copy-input.bin > raw.bin
strace -c -e trace=read,write,writev ./target/release/bytecopy buffered copy-input.bin > buffered.bin
cmp copy-input.bin raw.bin
cmp copy-input.bin buffered.bin

Read the calls column in each summary. The trace includes selected syscalls from program startup as well as the copy itself. To inspect individual transfers, rerun without -c and add -yy to annotate descriptors with information about their targets. Check which calls use the input file and which write to the redirected output. Keeping output redirected to regular files makes the workloads comparable. If a raw copy already reads large blocks, adding buffering may yield similar counts. If the raw loop asks for small chunks, each successful request generally transfers less data. The buffered version can serve many small requests from one underlying read and combine many small writes into one transfer.

An interrupted call or a child terminated by a signal can change the result you see from these interfaces. Signals and sigaction explains how Linux delivers signals and how a program selects what happens when they arrive.

Key takeaways

  • fork creates a child process, and execve replaces the program in the calling process while keeping its PID.
  • A descriptor number identifies an entry in a process's descriptor table. An owned descriptor closes its entry on drop.
  • Raw I/O loops must handle short reads, short writes, and interrupted calls.
  • Syscall counts depend on the sizes and paths of the actual reads and writes.
Reflect
  1. Explain to a colleague, in two sentences: distinguish a program's exit code from the termination status its parent observes.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close