问题
From the POSIX (IEEE Std 1003.1-2008) section on mmap
:
The file descriptor fildes shall have been opened with read permission, regardless of the protection options specified.
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?
回答1:
But the next line states that :
If PROT_WRITE is specified, the application shall ensure that it has opened the file descriptor fildes with write permission unless MAP_PRIVATE is specified in the flags parameter as described below.
I think that the line that you have quoted means that atleast the file descriptor to the file should be opened with read permission.It clearly says that the applications should ensure that proper level of permissions are granted first.
To try this I opened the file in READ ONLY mode and passed that descriptor to the mmap.
fd= open(file_name,O_RDONLY);
mappedData = mmap(0,fdstat.st_size,PROT_READ|PROT_WRITE, MAP_SHARED,fd,0);
But when I run the program error is thrown, namely:
mmap: Permission denied
EDIT: Sorry I misinterpreted your question.
回答2:
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.
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.
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.
来源:https://stackoverflow.com/questions/20290678/why-does-mmap2-with-prot-write-only-require-a-readable-fd