免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 774 | 回复: 0
打印 上一主题 下一主题

System V共享内存区实例 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-01-04 18:52 |只看该作者 |倒序浏览

[color="#000066"]System V共享内存区实例
转自:http://blog.chinaunix.net/u/21158/showart_226270.html

使用共享内存的步骤还是相当简单的:
1、获得唯一的key值,书上提到ftok不一定能得到唯一的键值;
2、使用shmget创建或着获得共享内存区;
3、使用shmat将共享内存区附加到进程中;
4、使用共享内存区,。。。
5、与共享内存区脱离,但是记住这时共享内存区依然存在,必须等到内核重启。
6、申请的共享内存区的大小是有限制的。
#############IPCShm1.cc
#include
#include
#include
#include
#include
#include
#include
typedef struct{
char name[4];
int age;
}people;
int main(int argc, char *argv[])
{
int shm_id,i;
key_t key;
char temp;
people *p_map;
char *path = "/home/program/mmapfile.cc";
/*
使用 ftok根据path和作为项目标识符的单个字符生成key值确保进程间使用相同的 key
使用相同key值的shmget只会在第一次时创建新结构,*/
key = ftok(path,0);
if(key == -1)
{
  perror("ftok error \n");
  return -1;
  }
shm_id = shmget(key,4096,IPC_CREAT);
if(shm_id == -1)
{
  perror("shmget error \n");
  return -1;
}
p_map = (people*)shmat(shm_id,NULL,0);
temp = 'a';
for(i = 0; i
#include
#include
#include
#include
#include
/*完成从共享内存区的读出*/
typedef struct{
char name[4];
int age;
}people;
int main (int argc, char** argv)
{
  int shm_id, i;
  key_t key;
  people *p_map;
  char *path = "/home/program/mmapfile.cc";
  key = ftok(path,0);
  if(key == -1)
  {
   perror("ftok error \n");
   return -1;
  }
  shm_id = shmget(key,4096,IPC_CREAT);
  if(shm_id == -1)
  {
   perror("shmget error");
   return -1;
  }
  p_map = (people*)shmat(shm_id,NULL,0);
  for(i=0; i<10; i++)
  {
   printf("name:%s\t",(*(p_map+i)).name);
   printf("age:%d\n",(*(p_map+i)).age);
  }
  system("ipcs -m");
  if(shmdt(p_map) == -1)
  {
   perror("shmdt error\n");
   return -1;
  }
  system("ipcs -m");
  exit(EXIT_SUCCESS);
}

/
运行结果:
name:b  age:20
name:c  age:21
name:d  age:22
name:e  age:23
name:f  age:24
name:g  age:25
name:h  age:26
name:i  age:27
name:j  age:28
name:k  age:29

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x00000001 32768      root      600        655360     2
0x00020069 262145     root      0          4096       1


------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x00000001 32768      root      600        655360     2
0x00020069 262145     root      0          4096       0
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/24474/showart_226341.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP