Skip to content
systemcoding.dev
Systems Programming

Share Memory Between Processes with shm_open and mmap

Share memory between unrelated processes with POSIX shm_open, ftruncate and mmap, add a writer and a reader, and learn the cleanup with shm_unlink. Linux 6.12.

7 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the C, AMD and Intel logos.

Two processes that need to share a table of numbers or a large buffer do not have to pass it through a pipe. POSIX shared memory lets both map the same pages, so a store by one process is visible to the other at once, with no copy and no system call per access. This post builds a writer and a reader with shm_open(), ftruncate() and mmap() on Linux 6.12 with glibc 2.41, from shm_open(3) and shm_overview(7).

The choice of shared memory over other mechanisms is covered in IPC mechanisms compared. This post is the hands-on first step, and the next ones add synchronization with named semaphores and unnamed semaphores in shared memory.

How the pieces fit

A POSIX shared memory object is a named file-like object. On Linux it lives in a tmpfs mounted at /dev/shm, so a name such as /demo appears as /dev/shm/demo. You do not write to it with write(). You map it into your address space and use ordinary memory accesses.

Four calls do the work:

  1. shm_open(name, oflag, mode) creates or opens the object and returns a file descriptor.

  2. ftruncate(fd, size) sets its size. A new object has size zero, and mapping zero bytes or touching beyond the size ends in SIGBUS.

  3. mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0) maps it. MAP_SHARED is required for changes to be visible to others.

  4. shm_unlink(name) removes the name. The memory itself is freed once the last process unmaps it.

The name must start with a slash and contain no other slash, such as /demo. On older glibc versions you had to link with -lrt. Since glibc 2.34 the functions live in the main C library, so gcc alone is enough on Linux 6.12 with glibc 2.41.

A shared structure

Define the layout in a header both programs include. Never share raw pointers between processes, since the segment can map at a different address in each. Store offsets or plain values.

shared.hc
#ifndef SHARED_H
#define SHARED_H

#include <stdint.h>

#define SHM_NAME "/demo_counter"

struct shared {
    uint32_t magic;          /* set last by the writer: readers check it */
    uint32_t version;
    char     message[64];
    int64_t  values[4];
};

#define SHARED_MAGIC 0x53484d31u   /* "SHM1" */

#endif

The magic field is a simple handshake. The writer fills everything else first and sets magic last. A reader that sees the right value knows the other fields are in place. This is not a substitute for real synchronization when both sides keep writing, but it is enough for a one-shot publish.

The writer

writer.cc
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "shared.h"

int main(void)
{
    int fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0600);
    struct shared *sh;

    if (fd == -1) {
        perror("shm_open");
        return 1;
    }
    if (ftruncate(fd, sizeof *sh) == -1) {
        perror("ftruncate");
        return 1;
    }

    sh = mmap(NULL, sizeof *sh, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (sh == MAP_FAILED) {
        perror("mmap");
        return 1;
    }
    close(fd);                              /* the mapping stays valid */

    sh->version = 1;
    strncpy(sh->message, "hello from the writer", sizeof sh->message - 1);
    for (int i = 0; i < 4; i++)
        sh->values[i] = (int64_t)(i + 1) * 100;
    __atomic_store_n(&sh->magic, SHARED_MAGIC, __ATOMIC_RELEASE);

    printf("writer: published %zu bytes at %s\n", sizeof *sh, SHM_NAME);
    munmap(sh, sizeof *sh);
    return 0;
}

mode 0600 limits access to the owner, which is the safe default. The fresh object is zero-filled by the kernel, so unset fields read as zero. After mmap() succeeds the file descriptor is no longer needed, so it is closed. The release store of magic ensures that the earlier writes are visible to any reader that observes the new value with an acquire load.

The reader

reader.cc
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "shared.h"

int main(int argc, char **argv)
{
    int fd = shm_open(SHM_NAME, O_RDONLY, 0);
    struct shared *sh;
    int remove_after = argc > 1;

    if (fd == -1) {
        perror("shm_open");
        return 1;
    }

    sh = mmap(NULL, sizeof *sh, PROT_READ, MAP_SHARED, fd, 0);
    if (sh == MAP_FAILED) {
        perror("mmap");
        return 1;
    }
    close(fd);

    if (__atomic_load_n(&sh->magic, __ATOMIC_ACQUIRE) != SHARED_MAGIC) {
        fprintf(stderr, "reader: segment is not ready\n");
        return 1;
    }

    printf("reader: version %u\n", sh->version);
    printf("reader: message \"%s\"\n", sh->message);
    for (int i = 0; i < 4; i++)
        printf("reader: values[%d] = %lld\n", i, (long long)sh->values[i]);

    munmap(sh, sizeof *sh);
    if (remove_after)
        shm_unlink(SHM_NAME);
    return 0;
}

Run ./writer, then ./reader:

Text
writer: published 104 bytes at /demo_counter
reader: version 1
reader: message "hello from the writer"
reader: values[0] = 100
reader: values[1] = 200
reader: values[2] = 300
reader: values[3] = 400

The two integers and the 64-byte message take 72 bytes, which is already a multiple of 8, so the four int64_t values follow directly and occupy another 32 bytes. That makes sizeof 104, and the writer prints sizeof rather than a number typed by hand, so the line changes whenever the layout does.

Notice what happened: the writer exited, and the data was still there. The object lives in /dev/shm until someone removes it.

Shell
ls -l /dev/shm/demo_counter
Text
-rw------- 1 user user 104 Nov 23 12:05 /dev/shm/demo_counter

Running ./reader remove calls shm_unlink() after reading, and the file disappears. A second run then fails at shm_open() with No such file or directory.

Common mistakes

**Forgetting ftruncate().** mmap() of a zero-length object succeeds only if you map nothing useful, and touching the pages raises SIGBUS. Always set the size after creating. The creator sets it, and openers should check it with fstat() before mapping if the layout might differ.

**Mapping with MAP_PRIVATE.** Writes then go to a private copy, and the other process never sees them. The symptom is a reader that always sees zeros.

Opening read-only and mapping read-write. O_RDONLY with PROT_WRITE and MAP_SHARED fails with EACCES. The reader above uses PROT_READ only.

Pointers inside the segment. A pointer stored in the shared region is a number valid in one address space. The other process maps at another address. Use indexes into a shared array or offsets from the base.

No synchronization. Two processes updating the same field, or one reading a multi-field record while the other writes, produce torn values. The magic trick covers a one-time publish. For continuing updates use a semaphore or a mutex with the PTHREAD_PROCESS_SHARED attribute placed in the segment. Use unnamed semaphores in shared memory with sem_init shows one way.

Leaked objects. If a crash skips shm_unlink(), the object stays in /dev/shm and uses memory until removed. A stale object from an earlier run can also hold old data and an old size. Create with O_CREAT | O_EXCL when you need a fresh one, and handle EEXIST by unlinking and retrying.

Sizing and limits

The object's size is bounded by the tmpfs size limit on /dev/shm, by default half of physical memory, which df -h /dev/shm shows. Pages are allocated on first touch, so a 1 GiB ftruncate() costs little until you write. A process that creates a huge sparse object can still exhaust memory later when it fills it. In containers, /dev/shm is often only 64 MiB unless the runtime sets a larger size, a frequent cause of SIGBUS in programs that worked on a developer machine.

Cleaning up

shm_unlink() removes the name immediately. Processes that have it mapped keep their mapping and the pages are freed when the last one unmaps. After unlink a new shm_open() of the same name creates a different object. On the command line, rm /dev/shm/demo_counter does the same. List and remove stale IPC objects with ipcs and ipcrm covers the cleanup of both POSIX and System V objects.

When not to use shared memory

If the data is a small message stream, a pipe or a socket is simpler and handles flow control and peer failure for you. If the processes are related and short-lived, mmap() with MAP_SHARED | MAP_ANONYMOUS before fork() shares memory with no name and no cleanup. And if you need to share between threads of one process, you already have shared memory and need only a lock.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.