How to close a file descriptor with Nix?


#1

Nix (https://docs.rs/crate/nix/0.8.0) wraps the Linux fcntl open() API (https://docs.rs/nix/0.8.0/nix/fcntl/fn.open.html). Where is the corresponding Nix close() call, wrapping http://man7.org/linux/man-pages/man2/close.2.html?

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.


#2

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.


#3

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.


#4

This should handle things for you I believe: https://crates.io/crates/memmap


#5

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!