Skip to content
systemcoding.dev
Systems Programming

Size a shared memory object with ftruncate after shm_open

shm_open creates an object of size zero, so call ftruncate before mmap or the first touch of the mapping raises SIGBUS, on Linux with glibc 2.40.

1 min read
Summarize in AI

A new POSIX shared memory object is empty. shm_open gives you a descriptor to a file of length zero, and mapping it works, but touching any page past the end of the file kills the process with SIGBUS. Set the size with ftruncate first, then map it.

shmsize.cc
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void)
{
    int fd = shm_open("/demo", O_CREAT | O_RDWR, 0600);
    struct stat st;

    if (fd == -1 || ftruncate(fd, 4096) == -1) {
        perror("shm");
        return 1;
    }
    fstat(fd, &st);

    char *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (p == MAP_FAILED) {
        perror("mmap");
        return 1;
    }
    strcpy(p, "hello");
    printf("size %lld: %s\n", (long long)st.st_size, p);

    munmap(p, 4096);
    close(fd);
    shm_unlink("/demo");
    return 0;
}
Text
size 4096: hello

The leading slash in the name is required for portable code, and the name has no further slashes. Since glibc 2.34 the shm_* functions live in libc itself, so the old -lrt link flag is no longer needed; older systems still require it. The ftruncate also works the other way, shrinking the object, so a second process that maps it afterwards should read the size with fstat rather than assume a constant. See shm_open(3).

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 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.