内存映射文件mmap

一、简介

内存映射文件,是由一个文件到一块内存的映射。内存映射文件与虚拟内存有些类似,通过内存映射文件可以保留一个地址空间的区域,同时将物理存储器提交给此区域,内存文件映射的物理存储器来自一个已经存在于磁盘上的文件,而且在对该文件进行操作之前必须首先对文件进行映射。使用内存映射文件处理存储于磁盘上的文件时,将不必再对文件执行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()

在这里插入图片描述

更多请点击

发布了325 篇原创文章 · 获赞 148 · 访问量 88万+

猜你喜欢

转载自blog.csdn.net/m0_37886429/article/details/105136388
今日推荐