Part 2 of 7 · 2 min read
Shared memory
In plain words: Two offices in different buildings each have a private filing cabinet, and they can also both get a key to one shared cabinet in a third room. What is put into the shared cabinet is seen by both at once, with no courier. The analogy stops in one place: the offices see the cabinet at their own door numbers, and a process sees a shared region at its own virtual address, which can differ from the other's.
In terms of Level 6, each process has its own page table. A shared region is a range of virtual pages in each page table whose entries point to the same frames. A write by one process changes the frame, and the other process reads the new value on its next access. No system call is needed for the transfer, and no copy is made. The processes use ordinary loads and stores.
The kernel creates shared memory in three ways, and the next sections show the first two:
- An anonymous shared mapping made before
fork: parent and child inherit it. - A POSIX shared memory object with a name, which unrelated processes can open.
- A mapped file with
MAP_SHARED(page 4), which also persists in the file system.
Shared memory
Shared memory is a region of memory that the page tables of two or more processes map to the same physical frames, so that a store by one process is seen by the others through ordinary loads.
Example: a parent that maps an anonymous region with MAP_SHARED and then forks has a region that the child sees too.
Check yourself: 1. What do the page tables of two processes hold for a shared page? 2. Why is no system call needed to pass data through shared memory? 3. Why can a shared page have different virtual addresses in the two processes?