共享内存

来源:互联网 发布:杭州seo搜索优化 编辑:程序博客网 时间:2024/04/27 05:09

一. 共享内存介绍

系统V共享内存指的是把所有共享数据放在共享内存区域(IPC shared memory region),任何想要访问该数据的

进程都必须在本进程的地址空间新增一块内存区域,用来映射存放共享数据的物理内存页面。系统调用mmap()通

过映射一个普通文件实现共享内存。系统V则是通过映射shm文件系统中的文件实现进程间的共享内存通信。

也就是说,每个共享内存区域对应shm文件系统一个文件.



共享内存的函数有以下几个:

(1)int shmget(key_t key, int size, int shmflg),开辟或使用一块共享内存。

(2)void *shmat(int shmid, const void *shmaddr, int shmflg), 将参数shmid所指向的共享内存与当前进程连接。

当使用某共享内存时,需要先使用shmat,达成连接。

(3)int shmdt(const void *shmaddr),将先前用shmat连接的共享内存与当前进程解除连接。参数shmaddr为shmat返回的共享内存的地址。

在完成对共享内存的使用后,需要使用shmdt解除连接。

(4)int shmctl(int shmid, int cmd, struct shmid_ds *buf),控制内存的操作。当cmd为IPC_RMID时,删除shmid所指的共享内存。

这些函数的表头文件为<sys/ipc.h>和<sys/shm.h>.


进程通过调用shmget(Shared Memory GET,获取共享内存)来分配一个共享内存块。
该函数的第一个参数是一个用来标识共享内存块的键值。彼此无关的进程可以通过指定同一个键以获取对同一个共享内存块的访问。不幸的是,其它程序也可能挑选了同样的特定值作为自己分配共享内存的键值,从而产生冲突。用特殊常量IPC_PRIVATE作为键值可以保证系统建立一个全新的共享内存块。


----------------------------------我是分割线-------------------------------------------

进程A的代码:

 

C代码  收藏代码
  1. #include    <sys/types.h>  
  2. #include    <sys/ipc.h>  
  3. #include    <sys/shm.h>  
  4. #include    <stdio.h>  
  5. #include    <error.h>  
  6.   
  7. #define SHM_SIZE    4096  
  8. #define SHM_MODE    (SHM_R | SHM_W) /* user read/write */  
  9.   
  10. int main(void)  
  11. {  
  12.     int     shmid;  
  13.     char    *shmptr;  
  14.   
  15.     if ( (shmid = shmget(0x44, SHM_SIZE, SHM_MODE | IPC_CREAT)) < 0)  
  16.         perror("shmget");  
  17.   
  18.     if ( (shmptr = shmat(shmid, 0, 0)) == (void *) -1)  
  19.         perror("shmat");  
  20.       
  21.     /* 往共享内存写数据 */  
  22.     sprintf(shmptr, "%s""hello, world");  
  23.   
  24.     exit(0);  
  25. }  

 进程B的代码:

 

C代码  收藏代码
  1. #include    <sys/types.h>  
  2. #include    <sys/ipc.h>  
  3. #include    <sys/shm.h>  
  4. #include    <stdio.h>  
  5. #include    <error.h>  
  6.   
  7. #define SHM_SIZE    4096  
  8. #define SHM_MODE    (SHM_R | SHM_W | IPC_CREAT) /* user read/write */  
  9.   
  10. int main(void)  
  11. {  
  12.     int     shmid;  
  13.     char    *shmptr;  
  14.   
  15.     if ( (shmid = shmget(0x44, SHM_SIZE, SHM_MODE | IPC_CREAT)) < 0)  
  16.         perror("shmget");  
  17.   
  18.     if ( (shmptr = shmat(shmid, 0, 0)) == (void *) -1)  
  19.         perror("shmat");  
  20.   
  21.     /* 从共享内存读数据 */  
  22.     printf("%s\n", shmptr);  
  23.   
  24.     exit(0);  
  25. }  


0 0