线程的 mmap 中 MAP_PRIVATE 和 MAP_SHARED 之间的区别

difference between MAP_PRIVATE and MAP_SHARED in mmap for threads

文件'hello'的内容是hello

$ od -tx1 -tc hello 
0000000 68 65 6c 6c 6f 0a
          h   e   l   l   o  \n
0000006

下面是我对文件 'hello'.

进行一些更改的代码
static void *task();

int main(void)
{
    int *p;
    pthread_t Thread;
    int fd = open("hello", O_RDWR);
    if (fd < 0) {
        perror("open hello");
        exit(1);
    }
    p = mmap(NULL, 6, PROT_WRITE, MAP_PRIVATE, fd, 0);
    if (p == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }
    close(fd);
    pthread_create(&Thread, NULL, &task, p)
    printf("Help");
    pthread_join(Thread, 0);
    munmap(p, 6);
    return 0;
}

static void * task(int *r)
{
 r[0] = 0x30313233;
}

上面的代码我用了MAP_PRIVATE,子线程好像不行。 如果我将 MAP_PRIVATE 更改为 MAP_SHARED,我发现它与我预期的不同。

$ od -tx1 -tc hello
 0000000 33 32 31 30 6f 0a
           3   2   1   0   o  \n
 0000006

但我不知道它是怎么发生的。

这与线程无关,在主线程中修改也是一样的。 MAP_PRIVATE 的重点不是将修改传播到基础对象(在本例中为文件)。 the manual:

中对此进行了描述

MAP_PRIVATE - Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

换句话说,MAP_PRIVATE 为您的进程(在其所有线程中)和分叉的子进程提供私人使用的内存区域,这些区域不会被写入任何地方。您可以将其视为 malloc().

的替代方案

阅读 manual 总是一个好主意,因为它会准确地告诉您原因。

MAP_SHARED

Share this mapping. Updates to the mapping are visible to other processes that map this file, and are carried through to the underlying file. The file may not actually be updated until msync(2) or munmap() is called.

MAP_PRIVATE

Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file.