Copy-on-write file mapping on windows

≡放荡痞女 提交于 2021-02-19 04:01:46

问题


I have 3 processes communicating over named pipes: server, writer, reader. The basic idea is that the writer can store huge (~GB) binary blobs on the server, and the reader(s) can retrieve it. But instead of sending data on the named pipe, memory mapping is used.

The server creates an unnamed file-backed mapping with CreateFileMapping with PAGE_READWRITE protection, then duplicates the handle into the writer. After the writer has done its job, the handle is duplicated into any number of interested readers.

The writer maps the handle with MapViewOfFile in FILE_MAP_WRITE mode.

The reader maps the handle with MapViewOfFile in FILE_MAP_READ|FILE_MAP_COPY mode.

On the reader I want copy-on-write semantics, so as long the mapping is only read it is shared between all reader instances. But if a reader wants to write into it (eg. in-place parsing or image processing), the impacts should be limited to the modifying process with the least number of copied pages possible.

The problem
When the reader tries to write into the mapping it dies with segmentation fault as if FILE_MAP_COPY was not considered. What's wrong with the above described method? According to MSDN this should work...

We have the same mechanism implemented on linux as well (with mmap and fd passing in AF_UNIX ancillary buffers) and it works as expected.


回答1:


problem here that MapViewOfFile bad designed or/and documented. this is shell (with restricted functionality) over ZwMapViewOfSection. the dwDesiredAccess parameter of MapViewOfFile converted to Win32Protect parameter of ZwMapViewOfSection.

the FILE_MAP_READ|FILE_MAP_COPY combination converted to PAGE_READONLY page protection, because this you and get page fault on write.

you need use FILE_MAP_COPY only flag - it converted to PAGE_WRITECOPY page protection and in this case all will be work.

the best solution of course direct use ZwMapViewOfSection with PAGE_WRITECOPY page protection




回答2:


TL:DR: RbMm is correct, you must pass just FILE_MAP_COPY to MapViewOfFile to get copy-on-write behavior.

The current Microsoft documentation is incorrect, it incorrectly states that FILE_MAP_COPY can be OR'ed with FILE_MAP_<ALL_ACCESS|READ|WRITE>.

Looking at older versions of MSDN it correctly says that you must choose one of the access modes:

Type of access to the file view and, therefore, the protection of the pages mapped by the file. This parameter can be one of the following values.

  • FILE_MAP_WRITE
  • FILE_MAP_READ
  • FILE_MAP_ALL_ACCESS
  • FILE_MAP_COPY

No longer relevant but still surprising, on Windows 95/98/ME the copy-on-write behavior only applies to the file, writes are propagated to views in other processes!



来源:https://stackoverflow.com/questions/55018806/copy-on-write-file-mapping-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!