一、簡介
內存映射文件,是由一個文件到一塊內存的映射。內存映射文件與虛擬內存有些類似,通過內存映射文件可以保留一個地址空間的區域,同時將物理存儲器提交給此區域,內存文件映射的物理存儲器來自一個已經存在於磁盤上的文件,而且在對該文件進行操作之前必須首先對文件進行映射。使用內存映射文件處理存儲於磁盤上的文件時,將不必再對文件執行I/O操作,使得內存映射文件在處理大數據量的文件時能起到相當重要的作用。
內存映射mmap是Linux內核的一個重要機制,它和虛擬內存管理以及文件IO都有直接的關係。Linux的虛擬內存管理是基於mmap來實現的。vm_area_struct是在mmap的時候創建的,vm_area_strcut代表了一段連續的虛擬地址,這些虛擬地址相應地映射到一個後備文件或者一個匿名文件的虛擬頁。一個vm_area_struct映射到一組連續的頁表項。頁表項又指向物理內存page,這樣就把一個文件和物理內存頁相映射。
二、示例說明
1、創建一個臨時示例文件
#-*- coding:utf-8 -*-
with open("hello.txt", "w") as f:
f.write("flags specifies the nature of the mapping. MAP_PRIVATE creates a private copy-on-write mapping, so changes to the contents of the mmap object will be private to this process, and MAP_SHARED creates a mapping that's shared with all other processes mapping the same areas of the file. The default value is MAP_SHARED\n")
f.write("prot, if specified, gives the desired memory protection; the two most useful values are PROT_READ and PROT_WRITE, to specify that the pages may be read or written. prot defaults to PROT_READ | PROT_WRITE\n")
2、打開一個內存影射文件,並操作
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import mmap
with open("hello.txt", "r+") as f:
mm = mmap.mmap(f.fileno(), 0)
print(mm[:])
3、修改內存,就是修改文件
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import mmap
with open("hello.txt", "r+") as f:
mm = mmap.mmap(f.fileno(), 30,access=mmap.ACCESS_WRITE)
print(mm[:])
mm[6:15] = b'SPECIFIES' #索引從0開始的
print(mm.readline())
mm.close()