虽然请求的映射地址是页首,但是会使用偏移几页的地址。
我正在尝试做这样的事情:
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/