mmap 中的长度是字节数还是页数?

Is the length in mmap a number of bytes or a number of pages?

在函数中:

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

mmap中的参数length是代表字节数还是页数?另外,我可以像 malloc 一样使用 mmap 吗?有什么区别?

length参数以字节为单位。 Linux 手册页没有明确说明这一点,但 POSIX spec 说(强调我的):

The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes.

可以使用 mmap 作为分配内存的方式(您需要使用 MAP_ANONYMOUS 或映射 /dev/zero 设备),但一般情况下不这样做malloc 的一个很好的直接替代:

  • 映射将始终以页面为单位进行(因此系统会将 length 舍入到页面大小的下一个倍数),因此对于小分配来说效率非常低。

  • 您不能将 mmap 返回的指针传递给 reallocfree(请改用 mremapmunmap) .

  • munmap 实际上是 returns 系统内存,而 free 可能会将其分配给您的进程,并将其标记为可供将来调用使用至 malloc。这有利也有弊。一方面,如果您知道您将来不会需要该内存,那么让系统收回它是件好事。另一方面,每个 mmap/munmap 都需要一个系统调用,这相对较慢,而 malloc 可能无需系统调用就可以分配先前 freed 已经属于您的进程的内存.