如何将同一文件的不同区域映射到不同的内存地址?
如何将文件的不同部分映射到不同的内存区域?
我尝试使用此代码,但出现 File isn't
错误:
int fd = open(FN, O_RDONLY);
if (fd == -1) {
perror("");
exit(1);
}
void* retval;
retval = mmap((void*) 0x00401000, 0xb93, PROT_READ | PROT_EXEC, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x1000);
if (retval == MAP_FAILED) {
perror("Error mmap 1");
exit(1);
}
retval = mmap((void*) 0x00402000, 0x660, PROT_READ, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x2000);
if (retval == MAP_FAILED) {
perror("Error mmap 2");
exit(1);
}
第一个 mmap 工作正常;第二个失败,并显示文件存在
。如果我注释掉第一个,第二个就可以了。
无论我执行 MMAP_PRIVATE
还是 MMAP_SHARED
,我都会收到此错误。同样,如果我重用原始 fd,或打开同一文件的新 fd,我也会收到错误。
如何将同一文件的两个区域映射到不同的位置?为什么我不能直接执行此操作,因为 mmap 是只读的(没有 PROT_WRITE
)并且也是写时复制(MMAP_PRIVATE
)。
How can I mmap different parts of a file into different memory regions?
I tried with this code, but get File exists
errors:
int fd = open(FN, O_RDONLY);
if (fd == -1) {
perror("");
exit(1);
}
void* retval;
retval = mmap((void*) 0x00401000, 0xb93, PROT_READ | PROT_EXEC, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x1000);
if (retval == MAP_FAILED) {
perror("Error mmap 1");
exit(1);
}
retval = mmap((void*) 0x00402000, 0x660, PROT_READ, MAP_FIXED_NOREPLACE | MAP_PRIVATE, fd, 0x2000);
if (retval == MAP_FAILED) {
perror("Error mmap 2");
exit(1);
}
The first mmap works fine; the second fails with File exists
. If I comment out the first one, the second works.
I get this error whether I do MMAP_PRIVATE
or MMAP_SHARED
. Likewise, I get the error if I reuse the original fd, or open a new fd to the same file.
How can I mmap two regions of the same file to different places? Why can't I do this directly, given that the mmap is read only (no PROT_WRITE
) and also copy-on-write (MMAP_PRIVATE
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于 mmap 调用中的
length
字段,而不是它是同一个文件这一事实。请注意,长度为0xb932
、0x660
,但这些长度由 mmap 向上舍入为 0x1000。因此,页面最终会占用比预期更多的内存,从而导致冲突,由于 MAP_FIXED_NOREPLACE ,内核无法替换和修复。The problem is the
length
field in the mmap calls, not the fact that it's the same file. Note the length is0xb932
,0x660
, but these are rounded up by mmap to 0x1000. Thus, the pages end up taking more memory than expected, causing collisions, which, due toMAP_FIXED_NOREPLACE
, the kernel is unable to replace and fix.