Chinaunix首页 | 论坛 | 博客
  • 博客访问: 104915
  • 博文数量: 50
  • 博客积分: 3120
  • 博客等级: 中校
  • 技术积分: 800
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-25 16:40
文章存档

2011年(1)

2009年(9)

2008年(40)

我的朋友

分类: LINUX

2008-09-25 17:18:44

使用共享内存的步骤还是相当简单的:
1、获得唯一的key值,书上提到ftok不一定能得到唯一的键值;
2、使用shmget创建或着获得共享内存区;
3、使用shmat将共享内存区附加到进程中;
4、使用共享内存区,。。。
5、与共享内存区脱离,但是记住这时共享内存区依然存在,必须等到内核重启。
6、申请的共享内存区的大小是有限制的。
#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共享内存区是放在内核当中的,因此在内核重新引导之前,对数据的修改是一直保持的
,这也是我们的实验能够实现的原因,因为在第二个进程起动时,第一个进程已经运行结束了.
*/
#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

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