Virtual Memory

a memory-mapped file

Imagine being able to treat a book on a library shelf as if its pages were already lying open on your desk: you read or scribble on 'page 50' directly, and a librarian quietly keeps the shelf copy in sync, fetching pages onto your desk only as you flip to them. A memory-mapped file is this trick for files: a file on storage is mapped into a program's virtual address space so the program reads and writes it with ordinary memory accesses instead of explicit read/write calls.

Concretely, the OS sets up page-table entries so that a range of the process's virtual addresses corresponds to the file's contents — but initially those pages are marked not-present. The first time the program touches a byte in that range, a page fault brings in just that one page from the file (demand paging applied to a file). Reads return file data; writes modify the in-memory page, and the dirty page is written back to the file later (or on request). The whole file need never be in memory at once — only the pages actually accessed occupy frames, exactly as with any other paged memory.

Why it matters: memory-mapped files unify file I/O and memory access using the very same paging machinery, which is elegant and often fast. They make it natural to share a file's pages between processes (each maps the same frames, so changes are instantly visible — a clean inter-process communication and shared-library mechanism), and they let you work with files larger than RAM by paging in only the active parts. It is a vivid demonstration that virtual memory is not really about RAM versus disk at all, but about a uniform, translated, demand-driven view of storage. The honest caveat: faults still cost what faults cost, and write-back timing and consistency need care.

A program maps a 100 GiB log file into its address space on a 16 GiB machine, then jumps to byte 80,000,000,000 and reads it. Only the few pages around that offset fault in; the rest of the file never enters RAM.

A file becomes addressable memory; only touched pages are paged in — file I/O via paging.

Memory-mapped files reuse the exact same fault-and-page-in machinery as demand paging — which is the deeper point: to the paging system, 'a page of a file' and 'a page of a program' are the same kind of thing, just backed by different storage.

Also called
mmap檔案記憶體映射