gpt4 book ai didi

c++ - 为什么我们可以映射到一个文件但超过文件大小?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:15 25 4
gpt4 key购买 nike

例如。

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。但它仍然有效?

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

谢谢

最佳答案

mmap 的签名是:

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

引用 Michael Kerrisk 的话:

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)

引用罗伯特·洛夫的话:

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)

关于c++ - 为什么我们可以映射到一个文件但超过文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47604431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com