Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4566121
  • 博文数量: 385
  • 博客积分: 21208
  • 博客等级: 上将
  • 技术积分: 4393
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-30 13:40
文章分类

全部博文(385)

文章存档

2015年(1)

2014年(3)

2012年(16)

2011年(42)

2010年(1)

2009年(2)

2008年(34)

2007年(188)

2006年(110)

分类: LINUX

2007-01-04 18:52:49


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 < 10; i++)
 {
  temp +=1;
  memcpy((*(p_map+i)).name,&temp,1);
  (*(p_map+i)).age = 20+i;
 }
 system("ipcs -m");
 if(shmdt(p_map) == -1)
 {
  perror("detach error");
 }
 system("ipcs -m");
}
/*
 System V共享内存区是放在内核当中的,因此在内核重新引导之前,对数据的修改是一直保持的
 ,这也是我们的实验能够实现的原因,因为在第二个进程起动时,第一个进程已经运行结束了.
*/
#########IPCShm2.cc
#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
阅读(2567) | 评论(0) | 转发(0) |
0

上一篇:每日一词(5)

下一篇:字符串的截取

给主人留下些什么吧!~~