为什么带有PROT_WRITE的mmap(2)只需要可读的fd? [英] Why does mmap(2) with PROT_WRITE only require a readable fd?
问题描述
摘自POSIX(IEEE Std 1003.1-2008)部分 mmap
:
From the POSIX (IEEE Std 1003.1-2008) section on mmap
:
无论指定了什么保护选项,文件描述符fildes都必须已获得读取权限打开.
The file descriptor fildes shall have been opened with read permission, regardless of the protection options specified.
那是为什么?好像描述符打开O_WRONLY
并用PROT_WRITE
而不是PROT_READ
映射在权限方面应该没有问题,对吧?
Why is that? Seems like a descriptor opened O_WRONLY
and mapped with PROT_WRITE
and not PROT_READ
shouldn't be problematic with respect to permissions, right?
推荐答案
我认为这不是因为权限,而是因为虚拟内存的内部情况:实际RAM页面的分配是由首次访问mmaped页面时的页面错误触发的.这些页面充满了映射文件的内容.用零填充(如果O_WRONLY打开的文件被映射为PROT_WRITE)将是一个合理的实现,但是可能没有太多实际应用.
I think it is not because of permissions, but because of virtual memory internals: allocation of actual RAM pages is triggered by page faults on first access to mmaped pages. These pages are filled with contents of mapped file. Filling them with zeros (in case of O_WRONLY opened file is mapped PROT_WRITE) would be a reasonable implementation, yet likely it has not many real world applications.
例如,如果仅更改页面中的几个字节,则整个页面仍将被替换为msync()
或munmap()
.这意味着如果映射和修改了只写文件,则有效地它将破坏"实际文件,除非整个页面中都正确地存储了内存中的数据.
If for example just a few bytes in the page are changed, still the whole page will be owerwritten at msync()
or munmap()
. This would mean that if write-only file is maped and modified, efectivelly it will "trash" the real file, unless whole pages are correctly filled with data in momory.
据我所知,页面不必为4KB或其他某个值,因此正确使用此类映射功能会很棘手.
As far as I know, page is not required to be 4KB or some other value, so using such mapping feature correctly would be tricky.
这篇关于为什么带有PROT_WRITE的mmap(2)只需要可读的fd?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!