Unix IPC之共享内存区(1)

1 共享内存区

共享内存区是可用IPC形式中最快的,只有映射和解除映射需要进入内核的系统调用,映射后对共享内存区的访问和修改不再需要系统调用(内核只要负责好页表映射和处理页面故障即可),但通常需要同步手段。

一个客户-服务器间传递文件数据的例子中,FIFO或消息队列等IPC方式通常需要4次内核-进程间的数据复制(但是Posix消息队列可使用内存映射I/O实现,就不一定4了),每次都需要切换地址空间,开销很大;共享内存区只需要2次跨内核的数据复制。



 

 

2  mmap

mmap的三个目的:

1.   使用普通文件以提供内存映射I/O。

2.   使用特殊文件以提供匿名内存映射。

3.   使用shm_open以提供Posix共享内存区。



 

3 munmap


 

4 msync

 

4 访问内存映射对象

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Map addresses starting near ADDR and extending for LEN bytes.
 * from OFFSET into the file FD describes according to PROT and FLAGS.
 * If ADDR is nonzero, it is the desired mapping address.
 * If the MAP_FIXED bit is set in FLAGS, the mapping will be at ADDR exactly (which must be
 * page-aligned); otherwise the system chooses a convenient nearby address.
 * The return value is the actual mapping address chosen or MAP_FAILED
 * for errors (in which case `errno' is set).  A successful `mmap' call
 * deallocates any previous mapping for the affected region.
 */
void *mmap (void *__addr, size_t __len, int __prot,
            int __flags, int __fd, __off_t __offset);
  • 文件大小filesize和内存映射区大小mmapsize可以不同

  • filesize > mmapsize,相当于将文件的部分映射为内存映射区

  • filesize < mmapsize,文件大小将会随着内存映射区访问指针的增长而增长(同步时会增长)

如果内存映射区的访问指针超过内存映射区的大小,超出部分的数据将会丢失,将无法同步到文件。

 

 





posted @ 2015-08-18 14:12  指上弹兵赵小括  阅读(437)  评论(0编辑  收藏  举报