Chinaunix首页 | 论坛 | 博客
  • 博客访问: 159790
  • 博文数量: 27
  • 博客积分: 97
  • 博客等级: 民兵
  • 技术积分: 314
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-19 19:34
个人简介

非攻飞攻,夜尽天明!

文章分类

全部博文(27)

文章存档

2014年(6)

2013年(21)

我的朋友

分类: LINUX

2013-06-23 10:36:31

(一)共享内存

1.shmget()创建共享内存

首先调用shmget()函数建立一块共享内存,大小为1024个字节,该函数返回创建的共享内存的标识符。

2. 调用fork产生一个子进程(生成者进程)

然后调用fork产生一个子进程(生成者进程)。子进程调用shmat()函数将该共享内存链接(attach)到自己的虚拟内存空间,即可通过普通的内存写操作(如strcpy等),在该共享内存写入数据。

3.shmdt()函数断开与该共享内存的链接

写完数据后子进程调用shmdt()函数断开与该共享内存的链接。

4. 父进程(消费者)调用shmctl得到关于共享内存的相关信息

父进程sleep,直到子进程完成上述操作。父进程(消费者)调用shmctl()函数得到关于这块共享内存的相关信息,并打印出来。

5. 父进程调用shmat()函数共享内存链接到自己的虚存空间

父进程调用shmat()函数将这块共享内存链接到自己的虚存空间,即可通过普通的内存读操作(如printf等),将该共享内存中的字符串读出来。

6. 父进程调用shmdtt()函数,销毁该共享内存

读完数据后,父进程调用shmdtt()函数,销毁该共享内存。

7代码实现共享内存通信

一个简单的共享内存示例。代码实现通过共享内存段通信的父进程和子进程

 

#include

#include

#include

#include

#define KEY 1234

#define SIZE 1024

int main()

{

int shmid;

char * shmaddr;

struct shmid_ds buf;

shmid = shmget(KEY,SIZE,IPC_CREAT|0600);

if(shmid == -1)

{

printf("create share memore failed:%s",strerror(errno));

return 0;

}

if(fork()==0)

{

sleep(2);

shmaddr=(char *)shmat(shmid,NULL,0);

if(shmaddr == (void *)-1)

{

printf("connect to the share memory failed:%s",strerror(errno));

return 0;

}

strcpy(shmaddr,"hello,this is shared data.\n");

shmdt(shmaddr);

exit(0);

}

else

{

wait(0);

shmctl(shmid,IPC_STAT,&buf);

printf("size of the share memory:shm_segsz=%dbytes\n",buf.shm_segsz);

printf("process id of the creator:shm_cpid=%d\n",buf.shm_cpid);

printf("process id of the last operator :shm_lpid=%d\n",buf.shm_lpid);

shmaddr=(char *)shmat(shmid,NULL,0);

if(shmaddr == (void *)-1)

{

printf("connect the share memory failed:%s",strerror(errno));

return 0;

}

printf("print the content of the share memory:");

printf("%s\n",shmaddr);

shmdt(shmaddr);

shmctl(shmid,IPC_RMID,NULL);

}

}

 

运行结果入下图:

 


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