Course contentsShow
← Computer Science
Lesson 1394 of 2,87232. File SystemsFree lesson

Memory-Mapped Files

Explore memory-mapped I/O where files are mapped into process address space for efficient access.

Memory-Mapped Files

What you'll learn: How operating systems can map file contents directly into a process's address space for faster, more convenient I/O.

The Core Idea

Instead of reading and writing files using traditional system calls like read() and write(), memory-mapped I/O lets you treat a file as if it were just an array in memory. The OS maps portions of the file directly into your process's virtual address space, so accessing the file becomes as simple as reading or writing regular memory locations.

How It Works

When you memory-map a file, the OS creates a mapping between virtual addresses in your process and the file's contents on disk. Behind the scenes:

  1. The MMU (Memory Management Unit) and page tables handle the translation
  2. When you access a mapped address, it may trigger a page fault if that portion isn't yet loaded
  3. The OS loads the relevant file data into a physical page frame
  4. Your program continues, reading or writing memory normally
  5. Modified pages are eventually written back to the file (either on explicit flush or when unmapped)

The Analogy

Think of a traditional file like a book in a library: you request specific pages, wait for them to arrive, copy information, and return them. A memory-mapped file is like having the book open on your desk—you flip directly to any page instantly, without ceremony.

Advantages

  • Performance: Eliminates copying data between kernel and user space
  • Convenience: Use simple pointer operations instead of system calls
  • Sharing: Multiple processes can map the same file for efficient inter-process communication
  • Demand paging: Only the parts you access are loaded

Key Takeaway: Memory-mapped files blur the line between memory and storage, providing transparent, efficient file access through your process's address space using the virtual memory subsystem you've already learned.