我一直在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_FAILED
,errno
= 22(EINVAL
)。 OS X man page for mmap
似乎表明这应该有用(它甚至在MAP_PRIVATE
标志的描述中提到了写时复制),并且我已经尝试了各种不同的标志来调用mmap
,但似乎没有任何效果。有什么想法吗?
答案 0 :(得分:3)
使用带有shm_open
和MAP_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_open
和MAP_SHARED
会产生MAP_PRIVATE
,但使用Invalid file descriptor
和MAP_SHARED
则不会。我不清楚这是一个错误,还是设计 - 虽然行为看起来不正确。