linux - 我可以使用对 munmap() 的单个调用来取消映射位于连续虚拟内存范围内的两个内存映射吗?

标签 linux macos posix mmap

例如,如果我这样做:

  char *pMap1;          /* First mapping */
  char *pReq;           /* Address we would like the second mapping at */
  char *pMap2;          /* Second mapping */

  /* Map the first 1 MB of the file. */
  pMap1 = (char *)mmap(0, 1024*1024, PROT_READ, MAP_SHARED, fd, 0);
  assert( pMap1!=MAP_FAILED );

  /* Now map the second MB of the file. Request that the OS positions the
  ** second mapping immediately after the first in virtual memory.  */
  pReq = pMap1 + 1024*1024;
  pMap2 = (char *)mmap(pReq, 1024*1024, PROT_READ, MAP_SHARED, fd, 1024*1024);
  assert( pMap2!=MAP_FAILED );

  /* Unmap the mappings created above. */
  if( pMap2==pReq ){
    munmap(pMap1, 2 * 1024*1024);
  }else{
    munmap(pMap1, 1 * 1024*1024);
    munmap(pMap2, 1 * 1024*1024);
  }

并且操作系统确实将我的第二个映射放在请求的位置(所以 (pMap2==pReq) 条件为真),将调用 munmap() 用于释放分配的所有资源?

Linux 手册页说“munmap() 系统调用删除映射 对于指定的地址范围...”,这表明这将起作用, 但我还是有点紧张。即使它在 Linux 上运行, 有人知道这可能有多便携吗?

非常感谢。

最佳答案

glibc 手册说没问题:

munmap removes any memory maps from (addr) to (addr + length). length should be the length of the mapping.

It is safe to unmap multiple mappings in one command, or include unmapped space in the range. It is also possible to unmap only part of an existing mapping. However, only entire pages can be removed.

关于linux - 我可以使用对 munmap() 的单个调用来取消映射位于连续虚拟内存范围内的两个内存映射吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15716664/

相关文章:

java - MACOS 上的 HAVE 权限错误

c - pselect 通知两个管道读端文件描述符,即使只有一个写端被写入

c - `read()` 使用什么返回值?

python - Bash:按字节区分大小写的排序命令或使用 python 排序命令对文本文件进行排序

c - 系统调用返回值和errno

正确的 kill syscall linux 使用模式

java - Java 系统属性存储在 Mac 上的什么位置?

linux - 搜索函数调用 submit_bio

linux - cd Desktop 在终端中给出错误 no such file/directory

c - "#define _GNU_SOURCE"意味着什么?