Chinaunix首页 | 论坛 | 博客
  • 博客访问: 260178
  • 博文数量: 84
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 927
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-06 23:00
个人简介

growing

文章分类

全部博文(84)

文章存档

2017年(6)

2016年(61)

2015年(17)

我的朋友

分类: LINUX

2016-07-06 21:59:37

特点:
1.自己维护(不保证临界资源同步、互斥,可自己用信号量来维护)
2.不用拷贝数据,所以很快

ipcs -m 查看共享内存
ipcrm -m 删除共享内存

使用例子:

  1. #include"common.h"

  2. static int comm_shm(int size,int flag)
  3. {
  4.     key_t key = ftok(_PATH_,_PROJ_ID_);
  5.     if(key == -1){
  6.         printf("%s\n",strerror(errno));
  7.         return -1;
  8.     }
  9.     int shm_id = shmget(key,size,flag);
  10.     if(shm_id == -1){
  11.         printf("%s\n",strerror(errno));
  12.         return -2;
  13.     }
  14.     return shm_id;
  15. }

  16. int creat_shm(int size)
  17. {
  18.     int flag = IPC_CREAT|IPC_EXCL|0666;
  19.     return comm_shm(size,flag);
  20. }

  21. int get_shm(int size)
  22. {
  23.     int flag = IPC_CREAT;
  24.     return comm_shm(size,flag);

  25. }

  26. int destory_shm(int shm_id)
  27. {
  28.     if(shmctl(shm_id,IPC_RMID,0) == -1){
  29.         printf("%s\n",strerror(errno));
  30.         return -1;
  31.     }
  32.     return 0;
  33. }

  34. void* attach(int shm_id)
  35. {
  36.     void* mem = NULL;
  37.     if(mem = shmat(shm_id,NULL,0)){
  38.         return mem;
  39.     }
  40.     return NULL;
  41. }

  42. int detach(void * addr)
  43. {
  44.     return shmdt(addr);
  45. }

 client

  1. #include"common.h"

  2. int main()
  3. {
  4.     int size = 1024;
  5.     int shm_id = creat_shm(size);
  6.     sleep(10);
  7.     char* mem = (char*)attach(shm_id);
  8.     memset(mem,'\0',size);

  9.     int count = 10;
  10.     while(count--){
  11.         printf("%s\n",mem);
  12.         sleep(1);
  13.     }

  14.     detach(mem);
  15.     destory_shm(shm_id);
  16.     return 0;
  17. }

server

  1. #include"common.h"

  2. int main()
  3. {
  4.     int size = 1000;
  5.     int shm_id = get_shm(size);
  6.     sleep(5);
  7.     char* mem = (char*)attach(shm_id);
  8.     memset(mem,'\0',size);
  9.     int index = 0;
  10.     int count = 10;
  11.     while(count--){
  12.         mem[index++] = 'A';
  13.         mem[index] = '\0';
  14.         sleep(1);
  15.     }
  16.     detach(mem);
  17.     return 0;
  18. }



阅读(1564) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~