我正在尝试将一个 64M 文件映射到内存中,然后对其进行读写。但是有时这个文件中的某个范围将不再被使用,所以我打电话fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 16 << 20, 16 << 20);
释放它里面的一个 16M 范围。
但是,我发现内存消耗似乎没有改变(来自free -m
和来自cat /proc/meminfo
)。
我知道 fallocate 会在文件中挖一些洞,并将这些范围返回给文件系统。但我不确定它是否会减少映射文件的内存消耗。
如果它不减少内存消耗,那么这样的范围在哪里?另一个进程能否获得先前分配给它的底层内存?
big.file 是一个普通的 64M 文件而不是稀疏文件
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <linux/falloc.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
uint8_t *addr;
int fd = open("home/big.file", O_RDWR | O_CREAT, 0777);
if (fd < 0)
return -1;
addr = (uint8_t *)mmap(NULL, MMAP_SIZE , PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (addr < 0)
return -1;
printf("data[0x%x] = %d\n", offset, addr[offset]);
getchar();
fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 16 << 20, 16 << 20);
getchar();
close(fd);
return 0;
}