mmap能够通过将磁盘上的文件映射到内存中,通过指针访问文件内容。这样能够达到快速处理文件。
包含的头文件为#include <sys/mman.h>,主要使用的函数有:
//打开文件,获取文件描述符
int open(const char *pathname, int flags);
//获取文件字节数
int stat(const char *restrict path, struct stat *restrict buf);
//使用mmap将对应的文件映射到本进程内存
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
//解除隐射才能释放内存空间
int munmap(void *addr, size_t length);
//关闭文件
int close(int fd);
注意:
使用完mmap之后,要记得使用munmap函数释放内存空间,否则就会产生内存泄露,而且此内存泄露不易发现,使用valgrind也没能查出来。
以下以我处理pcap文件的函数为例,展示mmap的使用方法,示例代码片段如下:
#include <sys/mman.h>
#include <sys/stat.h>
#include <pc