c - Mmap 不使用给定的地址

标签 c mmap memory-mapping

虽然请求的映射地址是页首,但是会使用偏移几页的地址。

我正在尝试做这样的事情:

char *mapped = mmap(base, page_size, PROT_NONE, MAP_SHARED,
                    file_handle, 0);
printf("Base  : %p\n", base);
printf("Mapped: %p\n", mapped);

示例输出(page_size = 4096 = 0x1000):

Base  : 0x7f22a1047000
Mapped: 0x7f22a1045000

偏移量为 2 页。这似乎也随 length 而变化。例如,如果我尝试映射 4 页而不是一页,则输出变为:

Base  : 0x7fd24d994000
Mapped: 0x7fd24d98f000

这是 5 页偏移量。

为什么会这样?

最佳答案

因为OS是,当你没有特别要求一个固定地址的映射时,可以自由选择一个对自己方便的地址;来自 mmap(2) 手册页:

MAP_FIXED
          Don't interpret addr as a hint: place the mapping at exactly that
          address.  addr must be a multiple of the page size.  If the memory
          region specified by addr and len overlaps pages of any existing
          mapping(s), then the overlapped part of the existing mapping(s) will be
          discarded.  If the specified address cannot be used, mmap() will fail.
          Because requiring a fixed address for a mapping is less portable, the
          use of this option is discouraged.

如果您不需要那个确切的地址,最好让系统选择它(老实说,在大多数情况下应该是这样)。

关于c - Mmap 不使用给定的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12025867/

相关文章:

c - 使用文件描述符使用 mmap 共享结构数组

linux-kernel - 如何使用 mmap 共享用户空间和内核线程

linux -/proc/self/maps 中的 "---p"权限是什么意思?

c - GDB 不允许我读取 argv 内存段

c++ - C/C++ 转换为 const 怪异

file - 为什么使用 mmap 而不是 fread?

c++ - 访问内存映射寄存器

windows - 如何在Windows进程之间传输敏感数据?

c - 将 int16_t 哈希为 uint64_t

c - C 中的 GLUT 屏幕截图