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.
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.
#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;
}size 4096: helloThe 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).