Hacker News new | past | comments | ask | show | jobs | submit login

Is this the general idea?

    int fd = shm_open("test", O_RDWR|O_CREAT, 0600);
    ftruncate(fd, 4096*2);

    char *part1 = mmap(NULL, 4096, PROT_WRITE|PROT_WRITE, MAP_SHARED, fd, 0);
    char *part2 = mmap(part1 + 4096, 4096, PROT_WRITE|PROT_WRITE, MAP_SHARED|MAP_FIXED, fd, 0);

    part1[0] = 'X';

    assert(part2 - part1 == 4096);
    assert(part1[0] == part2[0]);

    shm_unlink("test");



I've programmed with POSIX shared memory, and yes, that's the general idea.

A very important caveat is that the POSIX shared memory namespace is shared among all processes, so you need to wrap shm_open with a mkstemp()-style algorithm that generates a random name, opens with O_EXCL, and tries again if it fails. Unfortunately it's very easy to mess that up and introduce a security vulnerability.


It would be also prefferable to unlink just after /open/ call.

Wouldn't mkstemp("/dev/shm/tmp-XXXXXX") be enough. As strace tells /shm_open/ is just a wrapper for /open/ with /dev/shm/ prefix.


On Linux, shm_open is implemented with /dev/shm, but that's not the case on other platforms.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: