今天在使用mmap时发现打开或者创建一个新文件后,直接使用mmap,会报段错误。经过查找发现,不能对空文件进行mmap操作。解决方法也比较简单,在mmap之前进行ftruncate。
以下是一个正确的用例,如果把ftruncate去掉,则会报段错误。
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FILESIZE 5 * 1024 * 1024
int main(void)
{
int file = open("wt.txt", O_RDWR|O_CREAT);
/** @important
* 在这里先将文件的大小修改一下,
*/
ftruncate(file, FILESIZE);
char* base = (char*)mmap(NULL,
FILESIZE, PROT_READ|PROT_WRITE, MAP_SHARED, file, 0);
printf("base = %#x\n", base);
char* poffset = base;
int i = 0;
while (1) {
if (i == 10) i = 0;
if (poffset - base >= FILESIZE) return 0;
*poffset++ = i++;
}
munmap(base, FILESIZE);
return 0;
}