Call POSIX APIs Safely with the nix Crate
Use the nix crate to call POSIX functions like pipe, fork, waitpid and kill from Rust with typed arguments, Result errors and no raw unsafe libc calls.

The libc crate gives you every C function, with every C hazard attached: raw pointers, integer return codes you must check, and errno you must remember to read. Most Rust programs that need pipe, fork or kill should not call it directly. The nix crate wraps those functions in typed, Result-returning Rust, so a whole class of mistakes disappears at compile time. This post shows the pattern with working examples and says where nix stops helping.
The examples use nix 0.30 with Rust 1.85 on Linux 6.12. The crate keeps each area behind a Cargo feature, so a small program compiles only what it uses. Check the crate documentation for the feature list of the version you pin.
What nix gives you over libc
Compare the two for closing a file descriptor. With libc, you pass an i32, you get an i32 back, and nothing stops you using a closed descriptor afterwards:
unsafe { libc::close(fd) }; // returns -1 on error, errno holds the reasonWith nix, the function returns Result<(), Errno>, the error type is an enum with a name for every errno value, and, in current versions, functions that create descriptors return OwnedFd so the descriptor closes itself when dropped. Three gains come together:
Typed errors.
Errno::ENOENTis a value you can match on, not a number you compare to a constant.Typed arguments. Flags are
bitflagstypes such asOFlagandWaitPidFlag, so you cannot pass an unrelated constant.**No
unsafeat the call site** for the functions that are safe to expose.
Add it to Cargo.toml with only the features you need:
[dependencies]
nix = { version = "0.30", features = ["process", "signal", "fs"] }A pipe between parent and child
This program creates a pipe, forks, writes a message in the child and reads it in the parent. It is the smallest example that uses three subsystems at once.
use nix::sys::wait::waitpid;
use nix::unistd::{fork, pipe, ForkResult};
use std::fs::File;
use std::io::{Read, Write};
fn main() -> nix::Result<()> {
let (read_end, write_end) = pipe()?;
match unsafe { fork() }? {
ForkResult::Child => {
drop(read_end);
let mut out = File::from(write_end);
out.write_all(b"hello from the child\n").unwrap();
std::process::exit(0);
}
ForkResult::Parent { child } => {
drop(write_end);
let mut input = File::from(read_end);
let mut text = String::new();
input.read_to_string(&mut text).unwrap();
print!("{text}");
waitpid(child, None)?;
}
}
Ok(())
}hello from the childNotice what nix took care of. pipe() returns two OwnedFd values, and File::from turns each into a standard File without copying or casting. Each process drops the end it does not use, which matters: if the parent kept write_end open, read_to_string would never see end of file, because a pipe reports EOF only when every write end is closed. waitpid(child, None) reaps the child so it does not stay a zombie.
Why fork is still unsafe
fork is wrapped by nix but remains unsafe fn, and that is deliberate. After fork in a multithreaded program, the child holds copies of every lock that was held at the moment of the fork, and only the calling thread survives. If another thread held the allocator lock, the child's next println! or Vec::push can deadlock. The [fork documentation in nix](https://docs.rs/nix/latest/nix/unistd/fn.fork.html) states the rule: in a multithreaded process, the child may call only async-signal-safe functions until it calls exec. The example above is acceptable because the program has one thread and the child does little. Treat fork as safe only in that situation, or use std::process::Command and let std handle it, which a later post covers.
Signals with typed numbers
Sending a signal is where raw libc is most error-prone, because signal numbers differ across platforms. nix uses a Signal enum.
use nix::sys::signal::{kill, Signal};
use nix::unistd::getpid;
fn main() -> nix::Result<()> {
let me = getpid();
println!("pid is {}", me);
// Signal 0 checks that the process exists and we may signal it.
kill(me, None)?;
println!("process exists");
match kill(nix::unistd::Pid::from_raw(999_999), Signal::SIGTERM) {
Ok(()) => println!("signal sent"),
Err(e) => println!("kill failed: {e}"),
}
Ok(())
}pid is 48213
process exists
kill failed: ESRCH: No such processThe pid will differ on every run. Passing None as the signal sends signal 0, which delivers nothing and only reports whether the target exists, the same as kill -0 in a shell. The ESRCH message is the Display form of Errno::ESRCH, which is what kill(2) sets for a missing process. The man page lists the other errors.
Matching on Errno
Because errors are an enum, you can react to specific ones. A classic case is retrying an interrupted call.
use nix::errno::Errno;
use nix::unistd::read;
use std::os::fd::AsFd;
fn read_retry(fd: impl AsFd, buf: &mut [u8]) -> nix::Result<usize> {
loop {
match read(fd.as_fd(), buf) {
Err(Errno::EINTR) => continue,
other => return other,
}
}
}
fn main() -> nix::Result<()> {
let stdin = std::io::stdin();
let mut buf = [0u8; 16];
let n = read_retry(&stdin, &mut buf)?;
println!("read {n} bytes");
Ok(())
}read 6 bytesThat output assumes you typed hello and pressed Enter, which is six bytes. In nix 0.30, read takes a BorrowedFd, which is why the function accepts impl AsFd and calls as_fd(). Older nix versions took a raw RawFd, so code from before 0.27 will not compile unchanged. The loop on EINTR is the kind of detail std::fs hides for you but a direct nix call does not.
Pitfalls
Features hide functions. If an item is missing, you probably did not enable its feature. The error is "cannot find function" with no hint. Check the feature listed on the item's documentation page.
Version churn. nix moved from raw file descriptors to OwnedFd and BorrowedFd over several releases, and each move changed signatures. Pin a minor version and read the changelog before upgrading.
It is Unix only. The crate does not build on Windows. If your program must, guard it with cfg(unix) or use std alone.
Not everything is safe. Functions that take pointers the type system cannot check, or that change process-wide state like chroot, are still unsafe or have footguns documented on the item.
When to use libc instead
Use libc when nix has no wrapper for a call, when you need an exact C struct layout, or when you want zero dependencies. The cost is that you carry every check yourself. For a syscall nix lacks, a thin unsafe wrapper over libc::syscall in your own module, with one place that converts the return code to a Result, gives you most of the same safety.
Choosing between nix, rustix and libc
Three crates cover the same ground with different trade-offs, and it helps to pick on purpose. libc is the raw layer: every declaration, no safety, no opinions, and the smallest dependency. nix is the friendly layer: Unix-only, feature-gated, and shaped like the C API with Rust types. rustix is the strict layer: it can issue Linux syscalls directly without going through libc, takes BorrowedFd everywhere and has no raw pointers in its safe API. If your program is a typical Linux tool, nix is the easiest to read. If you are building a library that must not depend on a C library, or you want the strongest I/O-safety guarantees, look at rustix. In every case, keep the choice behind your own small module, so changing it later touches one file instead of the whole program.
Whichever you choose, write a test that exercises the error path. Calls like kill on a missing process, or open on a missing file, return Errno values on purpose, and a test that asserts the exact variant documents what your code does when the world is not friendly.


