//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); //新創建的文件或者已經存在的文件,都截斷為0if (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;
}
?