共享内存
系统接口
创建共享内存区域 shmget
//shmget所在的头文件和声明
#include <sys/ipc.h>
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg);
#include <sys/types.h>
#include <sys/ipc.h>
key_t ftok(const char *pathname, int proj_id);
关联共享区域 shmat
//shmat所在的头文件和声明
#include <sys/types.h>
#include <sys/shm.h>
void *shmat(int shmid, const void *shmaddr, int shmflg);
去除共享关联 shmdt
//shmdt所在的头文件和声明
#include <sys/types.h>
#include <sys/shm.h>
int shmdt(const void *shmaddr);
删除共享内存区域
ipcrm选项介绍
shmctl选项介绍
#include <sys/ipc.h>
#include <sys/shm.h>
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
int n = shmctl(shmid, IPC_RMID, nullptr);
assert(n != -1);
(void)n;
共享内存特性
- 无需多余拷贝:使用共享内存通信不需要任何接口,只要共享内存被映射到进程地址空间中,进程就能看到共享内存。
- 速度快:共享内存被映射到进程的地址空间中,进程就能看到共享内存,不涉及缓冲区,无需多余拷贝动作,因此共享内存通信速度很快。
- 无保护:使用共享内存通信不需要任何接口,因此共享内存不存在任何保护机制。