linux-内存映射mmap

         内存映射就是把非内存的文件映射到内存中,即在内存中创建一个外存的映象,内存中映射区域的改动会反映到外存文件中。可以把外存文件全部或者部分

映射到内存中,从而实现了内存对对外存文件的操作!内存映射可以加快对I/O的操作速度,可以使用指针操作文件,但是只能对在文件内可以定位的普通文件可以映射,

像管道,套接字,是不能够进行内存映射的。内存映射可以实现内存数据共享,并把数据保存到外存中去。

       #include <sys/mman.h>

       void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);

       int munmap(void *start, size_t length);

       map or unmap files or devices into memory

The  mmap() function asks to map length bytes starting at offset offset
       from the file (or other object) specified by  the  file  descriptor  fd
       into  memory,  preferably  at  address start.  This latter address is a
       hint only, and is usually specified as 0.  The actual place  where  the
       object is mapped is returned by mmap().

start为指针通常设为NULL,表示映射内存有系统决定。因为指定内存会经常出错。

length为内存映像占用的内存空间大小。以字节为单位。

port表示内存映像的安全性。

PROT_EXEC表示被映像内存可能有机器码,可执行。

PORT_NONE表示被映像内存不能被访问。

PORT_READ表示被映像内存可读

PORT_WRITE表示被映像内存可写


flag内存映像标志:

MAP_FIXED表示如果无法从start地址建立内存映像,则出错返回。

MAP_PRIVATE表示对内存映像进行的改动不反映到外存文件中。

MAP_SHARED表示对内存映像进行的改动反映到外存文件中。

note:     Share this mapping with all other processes  that  map  this
                  object.   Storing  to the region is equivalent to writing to
                  the file.  The  file  may  not  actually  be  updated  until
                  msync(2) or munmap(2) are called.

fd文件描述符

offset表示所映像的内容距文件头的距离。

 

  1
  2 #include <stdio.h>
  3 #include <unistd.h>
  4 #include <fcntl.h>
  5 #include <sys/mman.h>
  6 #include <sys/stat.h>
  7
  8 int main(void)
  9 {
 10         int fd;
 11         char *p;
 12         struct stat buf;
 13
 14         fd = open("./test.txt", O_RDWR);
 15         if (fd < 0)
 16         {
 17                 perror("open");
 18                 return 1;
 19         }
 20         fstat(fd, &buf);
 21
 22         p = mmap(NULL, buf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
 23         if (p == MAP_FAILED)
 24         {
 25                 perror("mmap");
 26                 return 2;
 27         }
 28
 29         p[5] = 'A';
 30
 31         munmap(p, buf.st_size);
 32         close(fd);
 33
 34         return 0;
 35 }
~                 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值