mmap映射实战举例
需求:在Linux环境下,需要打开一个文件,然后映射到内存中,接着在特定的地址偏移处写入内容,并且在此之前需要清空该位置的内容并填充为ff
,写完再做校验。
步骤:
- 打开文件:使用
open()
函数打开文件。 - 内存映射:使用
mmap()
函数将文件映射到内存中。 - 清空并填充:使用指针操作和
memset()
函数来清空并填充特定区域。 - 写入内容:将需要写入的内容通过指针写入到映射的内存区域。
- 同步内存映射:使用
msync()
函数确保内存中的数据写回到文件。 - 校验内容:使用
memcmp()
函数比较写入内容是否正确。 - 取消映射:使用
munmap()
函数取消映射。 - 关闭文件:使用
close()
函数关闭文件。
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
// 打开文件
int fd = open("wuyanzu.txt", O_RDWR);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// 获取文件大小
struct stat sb;
if (fstat(fd, &sb) == -1) {
perror("fstat");
exit(EXIT_FAILURE);
}
// 内存映射文件
void *mapped_area = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mapped_area == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
// 指定的偏移量和大小
off_t offset = 1024; // 举例的偏移量
size_t size_to_fill = 512; // 举例的填充大小
// 清空并填充为ff
memset((char *)mapped_area + offset, 0xff, size_to_fill);
// 写入内容到指定偏移量的位置
// 假设我们有一个字符数组作为示例内容
char content[] = "Hello, World!";
memcpy((char *)mapped_area + offset, content, sizeof(content));
// 将内存中的数据同步到磁盘上
if (msync(mapped_area, sb.st_size, MS_SYNC) == -1) {
perror("msync");
munmap(mapped_area, sb.st_size);
exit(EXIT_FAILURE);
}
//校验
if(memcmp((char *)mapped_area + offset, content, sizeof(content)) != 0)
{
perror("memcmp");
munmap(mapped_area, sb.st_size);
exit(EXIT_FAILURE);
}
// 取消映射
if (munmap(mapped_area, sb.st_size) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
// 关闭文件
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
return 0;
}