CSE Roadmap

Core tier · about 5 hours · 7 parts

Part 4 of 7 · 2 min read

POSIX shared memory

In plain words: An anonymous mapping can be shared only with children. Two programs that do not have a parent in common need a name. A POSIX shared memory object gives it. shm_open("/demo", ...) creates or opens an object with that name. On Linux, the objects appear as files in the directory /dev/shm, which is held in memory. The program then sets the size with ftruncate (a new object has size 0) and maps it with MAP_SHARED.

The writer:

int fd = shm_open("/demo", O_CREAT | O_RDWR, 0600);   /* a name, like a file in /dev/shm */
ftruncate(fd, 4096);                                  /* set its size */
char *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
strcpy(p, "hello from the writer");

The reader opens the same name, maps it, prints it and removes the name:

int fd = shm_open("/demo", O_RDWR, 0);
char *p = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
printf("reader: %s\n", p);
shm_unlink("/demo");                                  /* remove the name */

The output, with the writer run first and the reader second:

Step Result
Writer ends ls -l /dev/shm/demo shows a file of 4,096 bytes with mode -rw-------
Reader runs prints reader: hello from the writer
After the reader's shm_unlink /dev/shm/demo is gone, and a second reader fails with "No such file or directory"

Two facts come from this. The object lives on after the writer has exited: it is removed only by shm_unlink (or at reboot), so a program that crashes can leave objects behind. And the two processes mapped it at different virtual addresses. A run printed the address 0x7f7448082000 for the writer and 0x7f76c1180000 for the reader. The addresses differ because each process has its own layout (and the randomisation of Level 6 page 1). So a pointer stored inside the shared region is wrong in the other process. Store an offset from the start of the region instead.

POSIX shared memory object

A POSIX shared memory object is a named region of memory created with shm_open, sized with ftruncate, mapped with mmap(MAP_SHARED) by any process that knows the name, and removed with shm_unlink.

Example: the name /demo appears as the file /dev/shm/demo, and any process with permission can open it.

Check yourself: 1. Why does the program call ftruncate? 2. What removes a shared memory object? 3. Why must a shared region hold offsets and not pointers?