Use OwnedFd and BorrowedFd for File Descriptors in Rust
Stop passing raw i32 descriptors around. Use OwnedFd to close on drop and BorrowedFd to lend a descriptor safely, with the AsFd trait, since Rust 1.63.

A file descriptor is an i32 that the kernel gives you, and for decades C code has treated it as exactly that. You pass it around, you close it once if you remember, and you hope nobody else closes it first. Rust 1.63 added a way to give that integer an owner. OwnedFd closes the descriptor when it is dropped, and BorrowedFd lends it for a limited lifetime. This is the I/O safety model from RFC 3128, and it removes the two classic bugs: leaking a descriptor and closing one that is still in use.
The examples use Rust 1.85 on Linux 6.12 with the libc crate 0.2. Everything here lives in std::os::fd.
The problem with RawFd
RawFd is a type alias for i32. It carries no information about who may close it. Consider this function:
fn log_to(fd: RawFd, msg: &str) { /* write(fd, ...) */ }Does log_to close fd? Can the caller use fd afterwards? Is fd even open? The signature answers none of these, and a mistake produces the worst kind of bug: a descriptor number that is closed in one place and silently reused by an unrelated open in another, so a write meant for a log file lands in a socket.
Three types, three roles
The model separates ownership, borrowing and conversion.
| Type | Meaning | Closes on drop |
|---|---|---|
OwnedFd | This value owns the descriptor | Yes |
BorrowedFd<'a> | A descriptor owned by someone else, valid for 'a | No |
RawFd | A bare integer, no guarantees | No |
Two traits move between them. AsFd gives you a BorrowedFd from anything that holds a descriptor, and AsRawFd gives you the integer when you must call C. Every standard type that wraps a descriptor implements AsFd: File, TcpStream, UnixStream, Stdin, Stdout and others.
Write functions that borrow
The first rule is that a function that only uses a descriptor should accept impl AsFd. The caller keeps ownership, and the borrow checker guarantees the descriptor outlives the call.
use std::fs::File;
use std::io::Write;
use std::os::fd::{AsFd, AsRawFd};
fn describe(fd: impl AsFd) -> i32 {
fd.as_fd().as_raw_fd()
}
fn main() -> std::io::Result<()> {
let mut file = File::create("/tmp/fd-demo.txt")?;
file.write_all(b"hello\n")?;
let number = describe(&file);
println!("descriptor is open: {}", number >= 3);
drop(file);
Ok(())
}descriptor is open: trueThe exact descriptor number is usually 3 for the first file a program opens, but the example prints a boolean so the output is the same on every run. Because describe takes impl AsFd and the caller passes &file, nothing is moved and nothing is closed. The function cannot close the descriptor even if it wanted to, since BorrowedFd has no Drop that closes.
Take ownership when you must
A function that stores a descriptor, or hands it to another thread, should take OwnedFd. The move makes the transfer visible in the signature.
use std::fs::File;
use std::io::Read;
use std::os::fd::OwnedFd;
fn read_all(fd: OwnedFd) -> std::io::Result<String> {
let mut file = File::from(fd);
let mut text = String::new();
file.read_to_string(&mut text)?;
Ok(text)
}
fn main() -> std::io::Result<()> {
std::fs::write("/tmp/fd-owned.txt", "owned by read_all\n")?;
let fd: OwnedFd = File::open("/tmp/fd-owned.txt")?.into();
let text = read_all(fd)?;
print!("{text}");
Ok(())
}owned by read_allFile::open(...)?.into() converts the File into an OwnedFd with no system call, because both are wrappers around the same integer. read_all turns it back into a File to get the Read implementation. After the call, fd has been moved, so the compiler rejects any later use, and the descriptor closes when file goes out of scope inside read_all. The conversion works in both directions because File implements From<OwnedFd> and OwnedFd implements From<File>.
Duplicating a descriptor
Sometimes two owners need the same open file. OwnedFd::try_clone calls fcntl with F_DUPFD_CLOEXEC, producing a second descriptor that refers to the same open file description and has FD_CLOEXEC set. The two descriptors share one file offset, so reads through either advance both.
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
fn main() -> std::io::Result<()> {
std::fs::write("/tmp/fd-dup.txt", "abcdef")?;
let mut first = File::open("/tmp/fd-dup.txt")?;
let mut second = first.try_clone()?;
let mut a = [0u8; 2];
first.read_exact(&mut a)?;
println!("first read: {}", String::from_utf8_lossy(&a));
let mut b = [0u8; 2];
second.read_exact(&mut b)?;
println!("second read: {}", String::from_utf8_lossy(&b));
second.seek(SeekFrom::Start(0))?;
first.read_exact(&mut a)?;
println!("after seek: {}", String::from_utf8_lossy(&a));
Ok(())
}first read: ab
second read: cd
after seek: abThe second read returns cd, not ab, because the offset is shared. Seeking through second also moves the position seen by first. If you want independent offsets, open the path again instead of cloning. This surprises people who expect try_clone to behave like copying a struct.
Crossing into unsafe code
Two operations stay unsafe, because the compiler cannot verify the claim you make.
OwnedFd::from_raw_fd(raw) is a promise that this value is the sole owner of the descriptor and nobody else will close it. If another owner exists, the descriptor will close twice, and on a busy program the second close can hit a descriptor that was reopened for something else. BorrowedFd::borrow_raw(raw) is a promise that the descriptor stays open for the lifetime you pick. The lifetime is yours to get right.
The usual place you need them is at an FFI boundary, where C hands you a number:
use std::os::fd::{FromRawFd, OwnedFd, RawFd};
fn main() {
// Duplicate stdout so we own a descriptor of our own.
let raw: RawFd = unsafe { libc::dup(1) };
assert!(raw >= 0, "dup failed");
// SAFETY: dup returned a new descriptor that nothing else owns.
let owned = unsafe { OwnedFd::from_raw_fd(raw) };
println!("owned a duplicate of stdout");
drop(owned);
}owned a duplicate of stdoutThe SAFETY comment is the contract: dup returns a fresh descriptor nobody else holds, so taking ownership is correct. Put that comment on every from_raw_fd you write. When you only want to pass a descriptor to C, use as_raw_fd() and keep the owner alive for the whole call.
Pitfalls
**Do not mix into_raw_fd with forgetting.** IntoRawFd::into_raw_fd consumes the owner and gives you the integer without closing it, so you are now responsible. If you drop the integer, you leak the descriptor.
**A stored BorrowedFd cannot outlive its owner.** The lifetime parameter enforces this, so a struct holding one needs a lifetime annotation. If that feels clumsy, the struct probably should own an OwnedFd instead.
**RawFd still appears in older crates.** Many crates written before 1.63 take RawFd. Convert at the boundary with as_raw_fd() and keep the typed handle on your side.
Standard descriptors need care. std::io::stdout() implements AsFd, but dropping a File made from descriptor 1 closes it for the whole process. Borrow it, or try_clone first.
When not to bother
For code that only uses File, TcpStream and friends, you never see a raw descriptor, and nothing here applies. The model earns its keep where you call libc, nix or rustix directly, store descriptors in your own types, or pass them between threads and processes.
Passing descriptors to other threads and processes
Ownership makes the cross-thread case straightforward. An OwnedFd is Send, so you move it into a thread closure and the thread becomes the only closer. If two threads need the same descriptor at once, wrap the File in an Arc and share it by reference, or call try_clone and give each thread its own OwnedFd. Both approaches are checked by the compiler, which is the real gain over raw integers: a descriptor stored in a global i32 can be closed by one thread while another is mid-read.
Across process boundaries the rules change, because a descriptor number means nothing in another process. You pass it with a Unix socket and SCM_RIGHTS, which the kernel translates into a new number in the receiver, or you inherit it through fork and exec. For inheritance you must clear FD_CLOEXEC first, since Rust sets it by default. Remember that the child gets a duplicate, so the parent still owns its own copy and must drop it.


