在Mac OS X上使用mmap实现copy-on-write缓冲区

时间:2015-03-13 16:16:47

标签: c macos mmap copy-on-write

我一直在Linux上使用写时复制缓冲区,以下示例似乎按预期工作:

#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;
}

然而,在OS X(10.10)下,第二个mmap调用返回MAP_FAILEDerrno = 22(EINVAL)。 OS X man page for mmap似乎表明这应该有用(它甚至在MAP_PRIVATE标志的描述中提到了写时复制),并且我已经尝试了各种不同的标志来调用mmap,但似乎没有任何效果。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

使用带有shm_openMAP_SHARED的{​​{1}}似乎对文件描述符不利。使用MAP_PRIVATE是一种可行的解决方法:

open

结果:

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

使用munmap(buf2): 0 munmap(buf1): 0 shm_unlink: -1 shm_openMAP_SHARED会产生MAP_PRIVATE,但使用Invalid file descriptorMAP_SHARED则不会。我不清楚这是一个错误,还是设计 - 虽然行为看起来不正确。