Search code examples
linuxfwritemmap

How files are mapped to process address space?


How it is possible to memory map files to process address space? Generally Files are stored in secondary memory devices such as NAND, SD card etc. (Embedded environment) which does not provide byte by byte access? I need the pipeline how the file is updated in secondary storage when we update the memory which is mapped to file? And also why mmap is faster when compared to write() system call or fwrite() library call?


Solution

  • All you map is potentially copied to internal ram. So if you access some address of your prog file from sd card or whatever, a copy of the data is loaded into internal ram. How big the range really is, is only known by the os. Even if you reserve the place for the complete file, only a small part will be read if needed. If the cpu have a mmu, it can be simply implemented by page faults which results in reloads.

    Access is only faster, if you not directly store to the underlying physical device. So changes will only be done in ram, which is fast, and written later at once to the slower devices like serial flash or something else.

    A synchronization from changed mapped virtual ram to the underlying file can be done by msync http://man7.org/linux/man-pages/man2/msync.2.html

    If you need some basic information how ( virtual ) ram is addressed and how mmap maps to virtual ram, you can read this: https://www.xml.com/ldd/chapter/book/ch13.html