How to close a file descriptor with Nix?


Nix ( wraps the Linux fcntl open() API ( Where is the corresponding Nix close() call, wrapping

Note that Nix’ open() returns a RawFd. I thought that maybe the file is automatically closed when the RawFd exits scope, but when I looked into it, the RawFd boils down to a simple i32–I’m not seeing the mechanism for releasing the associated resources on scope exit.


Why are you using the nix crate for this rather than stdlib’s File? Anyway, you may be able to do File::from_raw_fd() and then let the resulting File go out of scope, which will close the file.


Because I’m new to Nix and to Rust and don’t yet know what I am doing? :blush:

I’ll test the File::from_raw_fd() call to see if that idea works–thank you!

In the meantime, how should I be opening a file, understanding that I’m using the call to open “/dev/mmap” to map MPU GPIO pins into user-space virtual memory.


This should handle things for you I believe:


Interesting. This looks like exactly what I’m already doing with my call to Nix’ (nix::sys::mman::mmap()) including the bit flags. I’d tried another crate earlier, but it had a large number of dependencies (including on nix) and failed to build. So I went straight to Nix from there.

If my current approach of using nix lets me down, I’ll take a look at memmap to see if it can get me there–thanks, @sfackler!