1. 共享存储结构
共享存储或者成为共享存储段是一个IPC 对象:使用shmget函数创建一个新的共享存储段,意味着内核分配一段物理内存与共享存储 id关联
不同的进程使用同一个shm_id 映射该段物理内存到各自的虚拟地址,从而实现进程间通信
2. 共享存储接口
#include <iostream>
using namespace std;
extern "C"
{
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
/*
int shmget(key_t key, size_t size, int shmflg);
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr);
*/
}
#define SHM_SIZE 10000
#define SHM_MODE 0600
int main()
{
key_t key = 999;
int shmid = shmget(key,SHM_SIZE,SHM_MODE|IPC_CREAT|IPC_EXCL);
if(-1 == shmid)
{
cout << "shm create failed ,exiting" << endl;
return -1;
}
void* ptr = shmat(shmid,NULL,0);
if((void*)-1 == ptr)
{
cout << "shm map failed" << endl;
goto Errend;
}
int *pint;
pint = (int*)ptr;
*pint = 100;
int res;
res = shmdt(ptr);
if(-1 == res)
{
cout << "shmdt failed" << endl;
}
Errend:
res = shmctl(shmid,IPC_RMID,NULL);
if(-1 == res)
{
cout << "shm delete failed ,exiting" << endl;
}
return 0;
}