线程的 mmap 中 MAP_PRIVATE 和 MAP_SHARED 之间的区别 [英] difference between MAP_PRIVATE and MAP_SHARED in mmap for threads

查看:302
本文介绍了线程的 mmap 中 MAP_PRIVATE 和 MAP_SHARED 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件'hello'的内容是hello.

The content of file 'hello' is hello.

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

下面是我对文件hello"进行一些更改的代码.

Below is my code to make some changes to the file '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,我会发现它产生了我所期望的不同.

The code above I used MAP_PRIVATE, and it seems that the child thread does not work. If I change MAP_PRIVATE to MAP_SHARED, I see it makes the difference I expect.

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

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

But I have no idea how it happens.

推荐答案

这个和线程无关,在主线程中修改也是一样的结果.MAP_PRIVATE 的重点不是将修改传播到底层对象(在本例中为文件).这在手册中有描述:

This has nothing to do with threads, you would have the same result if you did the modification in the main thread. The whole point of MAP_PRIVATE is not to propagate the modification to the underlying object (in this case, the file). This is described in the manual:

MAP_PRIVATE - 创建私有的写时复制映射.更新到映射对映射同一文件的其他进程不可见,并且不会传递到基础文件.未指定mmap() 调用后对文件所做的更改是否可见在映射区域.

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() 的替代方案.

In other words, MAP_PRIVATE gets you a region of memory for the private use of your process (in all its threads) and the forked subprocesses, which will not be written anywhere. You can think of it as an alternative to malloc().

这篇关于线程的 mmap 中 MAP_PRIVATE 和 MAP_SHARED 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆