歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下mmap函數的一個練習

Linux下mmap函數的一個練習

日期:2017/3/1 9:34:32   编辑:Linux編程

mmap函數用來將文件映射進內存。需要指出的是這裡的內存指的是虛擬內存。

mmap函數可以將一個文件的內容映射到內存,這樣就可以直接對該內存進行操作,從而省去IO操作。

下面是一個小例子:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<error.h>
#include<fcntl.h>
#include<sys/mman.h>
#include<unistd.h>
int main(int argc,char *argv[]){
int fd,len;
char *ptr;
if(argc<2){
printf("please enter a file\n");
return 0;
}
if((fd=open(argv[1],O_RDWR))<0){
perror("open file error");
return -1;
}
len=lseek(fd,0,SEEK_END);
ptr=mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);//讀寫得和open函數的標志相一致,否則會報錯
if(ptr==MAP_FAILED){
perror("mmap error");
close(fd);
return -1;
}
close(fd);//關閉文件也ok
printf("length is %d\n",strlen(ptr));
printf("the %s content is:\n%s\n",argv[1],ptr);
ptr[0]='c';//修改其中的一個內容
printf("the %s content is:\n%s\n",argv[1],ptr);
munmap(ptr,len);//將改變的文件寫入內存
return 0;
}

Copyright © Linux教程網 All Rights Reserved