用户空间用的mmap函数,是glibc 提供的
声明通过 man mmap 查找
#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
mmap 其中的一个用途(共享文件映射/私有文件映射) 是 访问文件
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
int main(int argc, char * argv[])
{
int fd, nread;
struct stat sb;
char *mapped;
if((fd = open(argv[1], O_RDWR|O_CREAT,S_IRWXU)) < 0){
perror("open") ;
return -1;
}
write(fd,"123456789ABC",strlen("123456789ABC"));
if((fstat(fd, &sb)) == -1 ){
perror("fstat") ;
return -2;
}
if (sb.st_size == 0)
sb.st_size == 0x1000;
if((mapped = mmap(NULL,
sb.st_size,
PROT_READ|PROT_WRITE,
MAP_SHARED,
fd,
0)) ==(void*) -1){
perror("mmap") ;
return -3;
}
mapped[0] = 'h';
mapped[1] = 'e';
mapped[2] = 'l';
mapped[3] = 'l';
mapped[4] = 'o';
mapped[5] = ' ';
mapped[6] = 'W';
mapped[7] = 'o';
mapped[8] = 'r';
mapped[9] = 'l';
mapped[10] = 'd';
if((msync((void *)mapped, sb.st_size, MS_SYNC)) == -1){
perror("msync") ;
return -4;
if((munmap((void *)mapped,sb.st_size)) == -1){
perror("munmap");
return -5;
}
}
close(fd);
return 0;
}