如何找到mmap()映射的数据个数?

How to find the number of data mapped by mmap()?

如果使用mmap()读取文件,如何找到mmap()映射的数据个数。

float *map = (float *)mmap(NULL, FILESIZE, PROT_READ, MAP_SHARED, fd, 0);

mmap system call does not read data. It just maps the data in your virtual address space (by indirectly configuring your MMU), 并且那个虚拟地址space被成功的mmap改变了。稍后,您的程序将读取该数据(或不读取)。在您的示例中,如果 mmap 成功,您的程序稍后可能会读取 map[356](并且您应该针对它的失败进行测试)。

仔细阅读 mmap(2). The second argument (in your code, FILESIZE) defines the size of the mapping (in bytes). You might check that it is a multiple of sizeof(float) and divide it by sizeof(float) to get the number of elements in map that are meaningful and obtained from the file. The size of the mapping is rounded up to a multiple of pages. The man page of mmap(2) 的文档说:

A file is mapped in multiples of the page size. For a file that is not a multiple of the page size, the remaining memory is zeroed when mapped, and writes to that region are not written out to the file.

数据映射到pages. A page is usually 4096 bytes. Read more about paging

页面大小由 getpagesize(2) or by sysconf(3)_SC_PAGESIZE 返回(通常为 4096)。

考虑读一些像 Operating Systems: Three Easy Pieces (freely downloadable) to understand how virtual memory works and what is a memory mapped file 这样的书。

在 Linux 上,/proc/ 文件系统(参见 proc(5))对于了解某些进程的虚拟地址 space 非常有用:尝试 cat /proc/$$/maps在您的终端中,阅读更多内容以了解其输出。对于 pid 1234 的进程,也可以尝试 cat /proc/1234/maps

从你的内部 process, you could even read sequentially the /proc/self/maps pseudo-file to understand its virtual address space, like here.