共享内存是运行在同一机器上的进程间通信最快的方式,因为数据不需要再不同的进程间复制。通常由一个进程创建一块共享内存区,其余进程对这块内存区进行读写。
示例1.1
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define IPC_KEY 0x00001234
int shm_id = -1;
int main(int argc, char *argv[])
{
shm_id = shmget(IPC_KEY, 32, IPC_CREAT | 0664);
if (shm_id < 0){
printf("shmget error!!!\n");
return -1;
}
void *ret_add = NULL;
ret_add = shmat(shm_id, NULL, 0);
if (-1 == (int)ret_add){
printf("shmat error!!!\n");
return -1;
}
int i = 0;
while (1){
sprintf((char*)ret_add, "test %d", i++);
sleep(1);
}
shmdt(ret_add);
shmctl(shm_id, IPC_RMID, NULL);
return 0;
}
示例1.2
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define IPC_KEY 0x00001234
int shm_id = -1;
int main(int argc, char *argv[])
{
shm_id = shmget(IPC_KEY, 32, IPC_CREAT | 0664);
if (shm_id < 0){
printf("shmget error!!!\n");
return -1;
}
void *ret_add = NULL;
ret_add = shmat(shm_id, NULL, 0);
if (-1 == (int)ret_add){
printf("shmat error!!!\n");
return -1;
}
int i = 0;
while (1){
printf("mem:[%s]\n", (char*)ret_add);
sleep(2);
}
return 0;
}
1.使用shmget创建共享内存(若已存在则打开共享内存)
2.使用shmat将共享内存映射到进程空间中
3.对共享内存进行读写
4.使用shmdt对共享内存解除映射
5.使用shmctl控制IPC_RMID来删除共享内存
Linux查看共享内存信息:ipcs -m