开发者

mmap(): what happens if underlying file changes (shrinks)?

开发者 https://www.devze.com 2023-03-24 01:08 出处:网络
If you memory map a file using mmap(), but then the un开发者_如何学JAVAderlying file changes to a much smaller size. What happens if you access a memory offset that was shaved off from the file?IBM sa

If you memory map a file using mmap(), but then the un开发者_如何学JAVAderlying file changes to a much smaller size. What happens if you access a memory offset that was shaved off from the file?


IBM says it is undefined http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Fapis%2Fmmap.htm

If the size of the mapped file is decreased after mmap(), attempts to reference beyond the end of the file are undefined and may result in an MCH0601 exception.

If the size of the file increases after the mmap() function completes, then the whole pages beyond the original end of file will not be accessible via the mapping.

The same is said in SingleUnixSpecification: http://pubs.opengroup.org/onlinepubs/7908799/xsh/mmap.html

If the size of the mapped file changes after the call to mmap() as a result of some other operation on the mapped file, the effect of references to portions of the mapped region that correspond to added or removed portions of the file is unspecified.

'undefined' or 'unspecified' means - the OS is allowed to start formatting of disk or anything. Most probable is SIGSEGV-killing your application.


It depends on what flags you gave to mmap, the man page:

MAP_SHARED Share this mapping. Updates to the mapping are visible to other processes that map this file, and are carried through to the underlying file. The file may not actually be updated until msync(2) or munmap() is called.

and

MAP_PRIVATE Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

So for MAP_PRIVATE, doesn't matter, each writer effectively has a "private" copy. (though it is only copies when a mutating operation occurs).

I would think that if you use MAP_SHARED, then no other process would be allowed to open the file with write privileged. But that's a guess.

EDIT: ninjalj is right, the file can be modified even when you mmap with MAP_SHARED.


According to the man pages mmap returns EINVAL error when you try to access an address that is too large for the current file mapping.

"dnotify" and "inotify" are the current file change notification services in the Linux kernel. Presumably, they would inform the mmap subsystem of changes to the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消