共享存储
共享存储允许两个或者多个进程共享一个给定的存储空间。因为数据不需要再客户进程和服务器进程之间复制,所以这一种最快的进程间通信。但要注意的是当服务器进程往共享存储区写数据时,客户端进程不应读这些数据。
例子:
模拟服务器端
#include <sys/ipc.h>
#include <sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int shmid;
char *shmaddr;
key_t key;
key=ftok(".",1);
shmid=shmget(key,1024*4,IPC_CREAT|0777);//创建共享内存空间
if(shmid==-1)
{
printf("创建共享内存失败!\n");
exit(-1);
}
shmaddr=shmat(shmid,0,0);//映射共享内存
printf("shmat ok !\n");
strcpy(shmaddr,"hello girl !");
sleep(10);//延时10s,等客户端读取这些数据
shmdt(shmaddr);//断开与共享内存的连接
shmctl(shmid,IPC_RMID,0);//删除共享内存
printf("demo quit ! \n");
return 0;
}
模拟客户端:
#include <sys/ipc.h>
#include <sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int shmid;
char *shmaddr;
key_t key;
key=ftok(".",1);
shmid=shmget(key,1024*4,0);//获取共享内存空间
if(shmid==-1)
{
printf("创建共享内存失败!\n");
exit(-1);
}
shmaddr=shmat(shmid,0,0);//映射共享内存
printf("shmat ok !\n");
printf("The data is %s \n",shmaddr);//输出共享内存里存储的数据。
shmdt(shmaddr);//断开与共享内存的连接
printf("demo quit ! \n");
return 0;
}