共享内存实现
共享内存实质是将内核中的一块内存映射到进程中的内存,操作本地内存就相当于操作共享内存。
使用共享内存步骤:
- 创建共享内存
#include <sys/ipc.h>
#include <sys/shm.h>
/*
创建共享内存:
int shmget(key_t key, size_t size, int shmflg);
函数描述:
创建或获得共享内存id
一般用法:
1、如果共享内存已经存在:
key_t key = 0x1234;
int shmId = shmget(key, 0, 0);
2、如果共享内存不存在:
int shmId = shmget(key, 100, IPC_CREAT|IPC_EXCL|0755);
3、如果不知道到底存不存在:
int shmId = shmget(key, 100, IPC_CREAT|0755);
*/
- 关联共享内存
#include <sys/types.h>
#include <sys/shm.h>
/*
连接共享内存:
void *shmat(int shmid, const void *shmaddr, int shmflg);
函数描述:
连接共享内存
参数:
shmid: shmget函数返回的共享内存的id值
shmaddr: 传NULL,表示让内核分配地址
shmflg:
SHM_RDONLY:只能对共享内存进行读操作
0:可读可写
返回值:
成功:返回关联共享内存的地址
失败:(void*)(-1)
*/
- 使用共享内存–读写共享内存
- 断开与共享内存的关联
#include <sys/types.h>
#include <sys/shm.h>
/*
int shmdt(const void *shmaddr);
参数:
shmaddr: shmat返回的内存地址
返回值:
成功:返回0
失败:返回-1,并设置errno
*/
- 删除共享内存
#include <sys/ipc.h>
#include <sys/shm.h>
/*
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
函数描述:
设置或删除共享内存
参数:
shmid:shmget函数返回的共享内存的id值
cmd:
IPC_STAT:获得共享内存的状态信息
IPC_SET:设置共享内存信息
IPC_RMID:删除共享内存
buf:
若cmd为IPC_RMID, 则buf为NULL
*/
示例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
int main()
{
// 创建共享内存 int shmget(key_t key, size_t size, int shmflg);
key_t key = 0x12345678;
int nShmId = shmget(key, 1024, IPC_CREAT | 0664);
if (0 > nShmId)
{
perror("shmget error");
return -1;
}
// 关联共享内存 void *shmat(int shmid, const void *shmaddr, int shmflg);
void *pShmAddr = shmat(nShmId, NULL, 0);
if ((void *)(-1) == pShmAddr)
{
perror("shmat error");
return -1;
}
// 读写共享内存
memcpy(pShmAddr, "hello world", sizeof("hello world"));
printf("shmId: %d, shmAddr: %p, content: %s\n", nShmId, pShmAddr, pShmAddr);
puts("按任意键:\n");
getchar();
// 断开共享内存关联 int shmdt(const void *shmaddr);
if (-1 == shmdt(pShmAddr))
{
perror("shmdt error");
return -1;
}
puts("按任意键:\n");
getchar();
// 删除共享内存 int shmctl(int shmid, int cmd, struct shmid_ds *buf);
if (-1 == shmctl(nShmId, IPC_RMID, NULL))
{
perror("shmctl error");
return -1;
}
return 0;
}