特点:
1.自己维护(不保证临界资源同步、互斥,可自己用信号量来维护)
2.不用拷贝数据,所以很快
ipcs -m 查看共享内存
ipcrm -m 删除共享内存
使用例子:
-
#include"common.h"
-
-
static int comm_shm(int size,int flag)
-
{
-
key_t key = ftok(_PATH_,_PROJ_ID_);
-
if(key == -1){
-
printf("%s\n",strerror(errno));
-
return -1;
-
}
-
int shm_id = shmget(key,size,flag);
-
if(shm_id == -1){
-
printf("%s\n",strerror(errno));
-
return -2;
-
}
-
return shm_id;
-
}
-
-
int creat_shm(int size)
-
{
-
int flag = IPC_CREAT|IPC_EXCL|0666;
-
return comm_shm(size,flag);
-
}
-
-
int get_shm(int size)
-
{
-
int flag = IPC_CREAT;
-
return comm_shm(size,flag);
-
-
}
-
-
int destory_shm(int shm_id)
-
{
-
if(shmctl(shm_id,IPC_RMID,0) == -1){
-
printf("%s\n",strerror(errno));
-
return -1;
-
}
-
return 0;
-
}
-
-
void* attach(int shm_id)
-
{
-
void* mem = NULL;
-
if(mem = shmat(shm_id,NULL,0)){
-
return mem;
-
}
-
return NULL;
-
}
-
-
int detach(void * addr)
-
{
-
return shmdt(addr);
-
}
client
-
#include"common.h"
-
-
int main()
-
{
-
int size = 1024;
-
int shm_id = creat_shm(size);
-
sleep(10);
-
char* mem = (char*)attach(shm_id);
-
memset(mem,'\0',size);
-
-
int count = 10;
-
while(count--){
-
printf("%s\n",mem);
-
sleep(1);
-
}
-
-
detach(mem);
-
destory_shm(shm_id);
-
return 0;
-
}
server
-
#include"common.h"
-
-
int main()
-
{
-
int size = 1000;
-
int shm_id = get_shm(size);
-
sleep(5);
-
char* mem = (char*)attach(shm_id);
-
memset(mem,'\0',size);
-
int index = 0;
-
int count = 10;
-
while(count--){
-
mem[index++] = 'A';
-
mem[index] = '\0';
-
sleep(1);
-
}
-
detach(mem);
-
return 0;
-
}
阅读(1604) | 评论(0) | 转发(0) |