//mmap、munmap函数的使用
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
void sys_err(char *str)
{
perror(str);
exit(1);
}
int main(void)
{
char *mem;
int len = 0;
int fd = open("hello244", O_RDWR|O_CREAT|O_TRUNC, 0644); //新创建的文件或者已经存在的文件,都截断为0
if (fd < 0)
sys_err("open error");
ftruncate(fd, 20); //文件大小为20
/*
len = lseek(fd, 3, SEEK_SET);
write(fd, "e", 1); //实质性完成文件拓展,大小为4
*/
printf("The length of file = %d\n", len);
mem = mmap(NULL, 20, PROT_WRITE, MAP_SHARED, fd, 0); //自己完成隐式转换
if (mem == MAP_FAILED) //出错判断
sys_err("mmap err");
close(fd); //可以关闭文件,以后通过映射区来操作文件
strcpy(mem, "xxx");
printf("%s\n", mem);
if (munmap(mem,20) < 0) //完全对应
sys_err("munmap");
return 0;
}