线程的 mmap 中 MAP

编程入门 行业动态 更新时间:2024-10-21 04:05:09
本文介绍了线程的 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

本文发布于:2023-11-26 00:22:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   mmap   MAP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!