What are memory-mapped files?

Answer

Memory-mapped files map a file (or device) into the virtual address space of a process. Once mapped, the file can be accessed using regular memory operations (pointer dereference, array indexing) rather than explicit read()/write() system calls. How it works: the OS maps the file's pages into the process's virtual address space. When the process accesses a page that isn't loaded, a page fault occurs → OS reads that portion of the file into memory. Modified pages may be written back to the file ("dirty page writeback"). mmap() system call (Unix): // Open file: int fd = open("data.bin", O_RDWR); // Map 1MB starting at file offset 0: void* ptr = mmap(NULL, 1024*1024, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); // Access file as memory! int* data = (int*)ptr; printf("%d\n", data[0]); // Read first int from file data[0] = 42; // Write directly to file! msync(ptr, 1024*1024, MS_SYNC); // Flush to disk munmap(ptr, 1024*1024); // Unmap close(fd);. MAP_SHARED vs MAP_PRIVATE: MAP_SHARED — changes written back to file; MAP_PRIVATE — COW, changes not written to file. Benefits: performance — avoid explicit read/write syscalls; large file access without reading all into memory; lazy loading via demand paging; file sharing between processes (MAP_SHARED); simplified programming (file = array). Uses: database files (PostgreSQL, SQLite use mmap), shared memory IPC, executable loading (loader mmaps .text, .data sections), large data files (genomics, scientific), shared libraries (single physical copy, multiple process mappings).