Implementing a copy-write buffer using mmap on Mac OS X

I play with copy-write buffers on Linux, and the following example works as intended:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define SIZE 4096

#define SHM_NAME "foobar"

int main(void)
{
    int fd = shm_open(SHM_NAME, O_RDWR | O_CREAT, 0666);
    int r = ftruncate(fd, SIZE);

    char *buf1 = mmap(NULL, SIZE, PROT_READ | PROT_WRITE,
                     MAP_SHARED, fd, 0);

    strcpy(buf1, "Original buffer");

    char *buf2 = mmap(NULL, SIZE, PROT_READ | PROT_WRITE,
                      MAP_PRIVATE, fd, 0);

    // At this point buf2 is aliased to buf1

    // Now modifying buf2 should trigger copy-on-write)...

    strcpy(buf2, "Modified buffer");

    // buf1 and buf2 are now two separate buffers

    strcpy(buf1, "Modified original buffer");

    // clean up

    r = munmap(buf2, SIZE);
    printf("munmap(buf2): %i\n", r);
    r = munmap(buf1, SIZE);
    printf("munmap(buf1): %i\n", r);
    r = shm_unlink(SHM_NAME);
    printf("shm_unlink: %i\n", r);

    return EXIT_SUCCESS;
}

However, in OS X (10.10), the second call mmapreturns MAP_FAILED, c errno= 22 ( EINVAL). the OS X man page formmap seems to suggest that this should work (he even mentions copy-on-write in the description MAP_PRIVATE), and I experimented with various different flags for calls mmap, but nothing works. Any ideas?

+4
source share
1 answer

, shm_open MAP_SHARED MAP_PRIVATE - . open - :

int fd = open(SHM_NAME, O_RDWR | O_CREAT, 0666);
...

:

munmap(buf2): 0
munmap(buf1): 0
shm_unlink: -1

shm_open MAP_SHARED MAP_PRIVATE Invalid file descriptor, MAP_SHARED MAP_SHARED, , . , - , .

+2

All Articles