介绍
内存和文件建立映射,直接用户层操作磁盘,跳过内核,就俩api
mmap 映射
mumap 取消映射
Demo
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
int main()
{
int fd = open("./1.txt", O_CREAT | O_RDWR, 0666);
if(fd == -1)
{
perror("open err:");
return -1;
}
ftruncate(fd, 1024);
char* ptr = reinterpret_cast<char*>(mmap(NULL, sizeof(1024), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
if(ptr == MAP_FAILED)
{
perror("mmap err:");
close(fd);
return -1;
}
close(fd);
strcpy(ptr, "hello world 1234567890");
ptr[0] = 'A';
munmap(ptr, 1024);
return 0;
}
本文介绍了Linux下内存映射API——mmap和munmap的使用方法,通过实例展示了如何创建文件与内存映射,修改映射内容,并演示了取消映射的过程。适合理解用户空间直接操作磁盘的开发者阅读。
382

被折叠的 条评论
为什么被折叠?



