Memory Mapped Files
- Many operating systems permit a file to be mapped into (virtual) memory.
- A range of memory addresses are now associated with the file.
- Reads and writes to those memory locations are treated as reads and writes to the file.
- Useful when you need to create a very large data structure but don't have enough real memory for it.
- You can create a file of appropriate size, mmap() it, and access your data structure using pointer arithmetic instead of file operators.
- Usage:
fd = open(filename, O_RDWR);
char *array = mmap(0, MEMSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
...
munmap(array, MEMSIZE);
close(fd);
- Often simpler than many random lseek()+read() calls on a file.
Many OSes use mmap() to run programs. Try truss ls.