Search code examples
clinuxoperating-systemoffsetmmap

What's the use of the offset in mmap?


I come across this from time to time in my operating systems class but the professor didn't explain it and I can't exactly find an explanation online. What exactly is the use of the offset in mmap ? Also this is for linux

Thanks


Solution

  • It lets you map a section of a file that doesn't necessarily start at the beginning.

    So

    fd = open("/path/to/myfile", O_RDONLY);
    ptr = mmap(NULL, 8192, PROT_READ, MAP_PRIVATE, fd, 4096);
    

    would map bytes 4096-12287 of the file into memory, and return a pointer to the address where they are mapped.

    This is useful, for instance, if you are loading a shared library. Some parts of the file may be headers or debug info that you don't need to map into memory.