Search code examples
rustmmap

Cannot write to memory mapped file


I am trying to write a byte vector, Vec<u8> to a memory-mapped file but I am stumped why it is not writing to the file. I have simplified the code to clearly show the method how I am writing to the memory mmapped file.

fn main() {
    let v : Vec<u8> = vec![0,0,0,1,0,0,0,2];
    let n = v.len();

    let f = OpenOptions::new()
        .read(true)
        .write(true)
        .truncate(true)
        .create(true)
        .open("test.dat")
        .unwrap();
    f.set_len(n as u64);

    let fd = f.as_raw_fd();

    let mmap = MemoryMap::new(n, &[MapReadable, MapWritable, MapFd(fd)]).unwrap();

    let mut data_ptr = mmap.data();

    unsafe { ptr::copy_memory(data_ptr, v.as_ptr(), n); }
}

It looks like it is the last line but don't know why it is not working nor how to fix it. :(


Solution

  • Ok I found out what the problem is. It passes MAP_PRIVATE by default so that's why it was not writing to it so I then ensured I added this to my 'mmap_options'

    MapOption::MapNonStandardFlags(libc::consts::os::posix88::MAP_SHARED)