1

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. :(

Yuri Astrakhan
  • 8,808
  • 6
  • 63
  • 97
jimjampez
  • 1,766
  • 4
  • 18
  • 29
  • What is this *data_ptr.offset(i) = b business? Wouldn't data_ptr[i] = b do the trick? – llogiq Mar 16 '15 at 12:58
  • Good question but, no, as you cannot index a `*mut u8`. – jimjampez Mar 16 '15 at 13:17
  • I tried using 'ptr::copy_memory' instead but still doesn't write so looks like there's something that's blocking it from writing it to the file. – jimjampez Mar 16 '15 at 13:46
  • Unrelated: `v.iter().enumerate()` let you iterate over tuples `(i, e)` avoiding the manual book-keeping required with `i` here. – Matthieu M. Mar 16 '15 at 14:02
  • Thanks Matthieu :) That will simplify my code a lot. I think I've got the problem now; it looks like it is not writing because it is passing MAP_PRIVATE by default. – jimjampez Mar 16 '15 at 14:05
  • possible duplicate of [How to create and write to memory mapped files?](http://stackoverflow.com/questions/28516996/how-to-create-and-write-to-memory-mapped-files) – Shepmaster Mar 16 '15 at 14:17

1 Answers1

2

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)
jimjampez
  • 1,766
  • 4
  • 18
  • 29