Linux mmap函式簡介

2021-09-08 22:18:40 字數 1410 閱讀 4897

一、簡介

linux提供了記憶體對映函式mmap, 它把檔案內容對映到一段記憶體上(準確說是虛擬記憶體上), 通過對這段記憶體的讀取和修改, 實現對檔案的讀取和修改, 先來看一下mmap的函式宣告:

原型: void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offsize);

返回值: 成功則返回對映區起始位址, 失敗則返回map_failed(-1).

引數:

flags: 對映區的特性, 可以是:

fd: 由open返回的檔案描述符, 代表要對映的檔案.

offset: 以檔案開始處的偏移量, 必須是分頁大小的整數倍, 通常為0, 表示從檔案頭開始對映.

下面說一下記憶體對映的步驟:

注意事項:

在修改對映的檔案時, 只能在原長度上修改, 不能增加檔案長度, 因為記憶體是已經分配好的.

二、示例

example1.c

#include#include

#include

#include

#include

#include

#include

int main(int argc,char *ar**)

if((fd=open(ar**[1],o_rdwr))<0

)

len=lseek(fd,0

,seek_end);

ptr=mmap(null,len,prot_read|prot_write,map_shared,fd,0);//

讀寫得和open函式的標誌相一致,否則會報錯

if(ptr==map_failed)

close(fd);

//關閉檔案也ok

printf("

length is %d\n

",strlen(ptr));

printf(

"the %s content is:\n%s\n

",ar**[1

],ptr);

ptr[

0]='

c';//

修改其中的乙個內容

printf("

the %s content is:\n%s\n

",ar**[1

],ptr);

munmap(ptr,len);

//將改變的檔案寫入記憶體

return0;

}

編譯

gcc -g -o example1 example1.c
執行

Linux mmap函式的記憶體對映

include 將檔案對映到記憶體 void mmap void addr,size t len,int prot,int flags,int fildes,off t off len 需要分配的記憶體長度 prot 期望的記憶體保護標識,不能與檔案開啟模式衝突 prot exec 頁內容可以被執行...

linux mmap驅動實現

在實現驅動程式的mmap函式時,要注意對映位址的轉換問題,見 定義乙個裝置結構體 這裡面這個memsize,最小都要是4096,因為記憶體對映是以頁為單位的。在實現 remap mmap函式時,如下 注意函式開頭的vma vm pgoff u32 virt to phys leedriverp me...

linux mmap驅動實現

在實現驅動程式的mmap函式時,要注意對映位址的轉換問題,見 定義乙個裝置結構體 cpp view plain copy struct leedriver 這裡面這個memsize,最小都要是4096,因為記憶體對映是以頁為單位的。在實現 remap mmap函式時,如下 cpp view plai...