例如,如果我这样做:
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/