为什么我们可以映射到文件但超过文件大小? [英] why we can mmap to a file but exceed the file size?

查看:111
本文介绍了为什么我们可以映射到文件但超过文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如.

fd = ::open ("/test.txt", O_RDONLY, 0);
struct stat buf;
fstat(fd, &buf);
char* addr = (char*)::mmap(NULL, buf.st_size + 10, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);

请注意,我在此处映射了 + 10 . 但这仍然有效吗?

Notice that I mapped + 10 here. But it still works?

为什么系统不应用任何检查? 危险吗?

Why system does NOT apply any check? Is it dangerous?

谢谢

推荐答案

mmap的签名为:

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);

引用Michael Kerrisk:

To quote Michael Kerrisk:

length参数指定映射的大小(以字节为单位). 尽管长度不必是系统页面大小的倍数 (由sysconf(_SC_PAGESIZE)返回),内核在以下位置创建映射 这种大小的单位,因此长度实际上是四舍五入到 页面大小的下一个倍数. -Linux编程接口(第49章)

The length argument specifies the size of the mapping in bytes. Although length doesn’t need to be a multiple of the system page size (as returned by sysconf(_SC_PAGESIZE)), the kernel creates mappings in units of this size, so that length is, in effect, rounded up to the next multiple of the page size. - The Linux Programming Interface (Chapter 49)

引用罗伯特·洛夫的话:

To quote Robert Love:

mmap()系统调用在页面上进行. addr和offset参数都必须在页面大小的边界上对齐.也就是说,它们必须是页面大小的整数倍.因此,映射是页面的整数倍.如果调用者提供的len参数未在页面边界上对齐(可能是因为基础文件的大小不是页面大小的倍数),则该映射将向上舍入到下一个完整页面.该添加内存中的最后一个有效字节与映射末尾之间的字节为零填充.从该区域读取的任何内容都将返回零.即使对该内存进行任何写操作,都不会影响该备份文件,即使该文件被映射为MAP_SHARED.只有原始的len字节会被写回到文件中. -Linux系统编程(第4章)

The mmap( ) system call operates on pages. Both the addr and offset parameters must be aligned on a page-sized boundary. That is, they must be integer multiples of the page size. Mappings are, therefore, integer multiples of pages. If the len parameter provided by the caller is not aligned on a page boundary—perhaps because the underlying file’s size is not a multiple of the page size—the mapping is rounded up to the next full page. The bytes inside this added memory, between the last valid byte and the end of the mapping, are zero-filled. Any read from that region will return zeros. Any writes to that memory will not affect the backing file, even if it is mapped as MAP_SHARED. Only the original len bytes are ever written back to the file. - Linux System Programming (Chapter 4)

这篇关于为什么我们可以映射到文件但超过文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆