I am trying to write data to a memory-mapped file in Rust but it won't memory map the specified file as it states the given fd is not available.
I can see it on the filesystem so it does exist with correct privileges. I suspect this is either a bug or I am not using the new IO API in the correct way.
mmap err = fd not available for reading or writing
Here's the code
use std::fs::File;
use std::os::MemoryMap;
use std::os::unix::prelude::AsRawFd;
use std::os::MapOption::{MapFd, MapWritable, MapReadable};
fn main() {
let f = File::create("test.dat").unwrap();
f.set_len(n as u64);
let fd = f.as_raw_fd();
let mmap = MemoryMap::new(n, &[MapReadable, MapWritable, MapFd(fd)]);
match mmap {
Ok(_) => println!("mmap success"),
Err(ref err) => println!("mmap err = {}", err),
}
}
Files created with
File::create
are in write-only mode, but you are attempting to map the file for both reading and writing. UseOpenOptions
to get a file with both modes:I figured this out by
Grepping the code for "fd not available for reading or writing", which leads to this line, which aligns to
ErrFdNotAvail
(could also have changedmmap err = {}
tommap err = {:?}
).Searching for that enum variant leads to this line, which maps the underlying
libc::EACCES
error.Checked out the man page for
mmap
to see whatEACCES
says: