简体   繁体   English

mmap文件以及该文件未支持的另一页

[英]mmap file with one additional page that is not backed by the file

I need to mmap a file in read-only mode but need an additional page at the end of the mapping that is \\0-ed out. 我需要以只读模式映射文件,但需要在映射末尾添加\\ 0-ed的附加页面。 My initial idea was to mmap an additional page and claim it by writing to it. 我最初的想法是映射另外的页面并通过写来声明它。

int file=::open(name,O_RDONLY);
size_t size=lseek(file,0,SEEK_END);
size_t pageSize=::sysconf( _SC_PAGESIZE);
int padding=size%pageSize;
size_t mapSize=size+padding+pageSize;
void* mapping=mmap(0,mapSize,PROT_READ|PROT_WRITE,MAP_PRIVATE,file,0);
*(static_cast<char*>(mapping)+size+padding+1)=0;

However, as stated in the mmap documentation I then get a SIGBUS when I write to the additional page (also when reading from there). 但是,如mmap文档中所述,当我写入附加页面时(以及从该页面读取时),我都会得到一个SIGBUS。

My question is, can I somehow claim an additional page after the file without modifying the actual file? 我的问题是,我可以在不修改实际文件的情况下以某种方式在文件后声明一个附加页面吗?

Linux supports MAP_FIXED flag that forces mmap() segment placement, so all you need is to correctly calculate address call second mmap() that will map anonymous page (currently your calculation of padding is incorrect). Linux支持MAP_FIXED标志,该标志强制执行mmap()段放置,因此,您所需mmap()就是正确计算将映射匿名页面的地址调用第二个mmap() (当前,您的padding计算不正确)。

int file = ::open("mmap", O_RDONLY);
size_t size = ::lseek(file, 0, SEEK_END);
size_t pageSize = ::sysconf(_SC_PAGESIZE);

int padding = pageSize - size % pageSize;
size_t mapSize = size + padding;

void* mapping = ::mmap(0, mapSize, PROT_READ | PROT_WRITE, 
                     MAP_PRIVATE, file, 0);
void* lastPage = static_cast<char*>(mapping) + mapSize;

void* mapping2 = ::mmap(lastPage, pageSize, PROT_READ | PROT_WRITE, 
                        MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);

* static_cast<char*>(mapping ) = 1;
* static_cast<char*>(mapping2) = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM