昨天晚上实验了一mmap的用法,在网上搜了一些资料,拿来都不能直接用,下面是在MacOS和Ubuntu都测试过可正确执行的代码。
实验过程中我一开始使用private模式映射文件,结果对内存的修改不会被同步到文件,具体原因有待研究。另外代码里面使用lseek和write来扩展文件大小,网上的资料还显示可以通过ftruncate函数来扩展文件大小,我挺好奇这两个函数哪个效率更高,以后有机会测试看看。
下面是实验代码(用--std=c99参数编译):
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#define FILE_LEN 1024
#define LDB_ERROR(where) { printf("%s: %s", where, strerror(errno)); exit(1); }
int main(int argc, char* argv[])
{
int file = open("./data.bin", O_RDWR | O_CREAT);
if (file == 0) {
LDB_ERROR("init file");
}
lseek(file, FILE_LEN, SEEK_SET);
write(file, "", 1);
//ftruncate(file, FILE_LEN);
void* pointer = mmap(NULL, FILE_LEN, PROT_READ | PROT_WRITE, MAP_SHARED, file, 0);
if (pointer == MAP_FAILED) {
LDB_ERROR("map file");
}
close(file);
memcpy(pointer, "Hello World", 11);
msync(pointer, FILE_LEN, MS_SYNC);
if (munmap(pointer, FILE_LEN) < 0) {
LDB_ERROR("unmap file");
}
return 0;
}
原标签已从 2023-12-16 存档快照 恢复。本文按原站快照恢复排版,并接回已核实的本地图片。查看恢复说明