tri*_*tan 5 linux mmap linux-kernel
代码片段在我的机器上运行良好(Linux/x86-64)
int main()
{
char* addr;
int rc;
int fd;
const size_t PAGE_SIZE = 4096; // assuming the page size is 4096
char buf[PAGE_SIZE];
memset(buf, 'x', sizeof(buf));
// error checking is ignored, for demonstration purpose
fd = open("abc", O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
ftruncate(fd, 0);
write(fd, buf, 4090);
// the file size is less than one page, but we allocate 2 page address space
addr = mmap(NULL, PAGE_SIZE * 2, PROT_WRITE, MAP_SHARED, fd, 0);
// it would crash if we read/write from addr[4096]
// extend the size after mmap
ftruncate(fd, PAGE_SIZE * 2);
// now we can access(read/write) addr[4096]...addr[4096*2 -1]
munmap(addr, PAGE_SIZE * 2);
close(fd);
exit(EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
但是 POSIX 说:
如果映射文件的大小在调用 mmap() 之后由于对映射文件的某些其他操作而发生变化,则对映射区域中与文件添加或删除部分相对应的部分的引用的影响是未指定的。
所以我想这不是一种便携的方式。但是它可以保证在 Linux 上工作吗?
| 归档时间: |
|
| 查看次数: |
1210 次 |
| 最近记录: |