#include <shm.h>
int main(int argc,char **argv)
{
int num;
int shmid_goods,shmid_index,semid;
char* shmaddr=NULL;
int* indexaddr=NULL;
int is_noexist=0;
num=10;
//create a shared memory as goods buffer
if((shmid_goods=createshm(".",'s',num))==-1)
{
if(errno==EEXIST)
{
if((shmid_goods=openshm(".",'s'))==-1)
{
exit(1);
}
}
else
{
perror("create shared memory failed\n");
exit(1);
}
}
//attach the shared memory to the current process
if((shmaddr=shmat(shmid_goods,(char*)0,0))==(char*)-1)
{
perror("attach shared memory error\n");
exit(1);
}
//create a shared memory as index
if((shmid_index=createshm(".",'z',2))==-1)
{
if(errno==EEXIST)
{
if((shmid_index=openshm(".",'z'))==-1)
{
exit(1);
}
}
else
{
perror("create shared memory failed\n");
exit(1);
}
}
else
{
is_noexist=1;
}
//attach the shared memory to the current process
if((indexaddr=shmat(shmid_index,(int*)0,0))==(int*)-1)
{
perror("attach shared memory error\n");
exit(1);
}
if(is_noexist)
{
indexaddr[0]=0;
indexaddr[1]=0;
}
//create a semaphore set including 3 semaphores
if((semid=createsem(".",'t',3,0))==-1)
{
if(errno==EEXIST)
{
if((semid=opensem(".",'t'))==-1)
{
exit(1);
}
}
else
{
perror("semget error:");
exit(1);
}
}
else
{
union semun arg;
//seting value for mutex semaphore
arg.val=1;
if(semctl(semid,0,SETVAL,arg)==-1)
{
perror("setting semaphore value failed\n");
return -1;
}
//set value for synchronous semaphore
arg.val=num;
//the num means that the producer can continue to produce num products
if(semctl(semid,1,SETVAL,arg)==-1)
{
perror("setting semaphore value failed\n");
return -1;
}
//the last semaphore's value is default
//the default value '0' means that the consumer is not use any product now
}
int goods=0;
while(1)
{
p(semid,2);
sleep(1);
p(semid,0);
//consumer is consuming a product
goods=shmaddr[indexaddr[1]];
printf("consumer:%d consumes a product[%d]:%d\n",getpid(),indexaddr[1],goods);
indexaddr[1]=(indexaddr[1]+1)%num;
v(semid,0);
sleep(1);
v(semid,1);
}
}

bzzzzl
- 粉丝: 55
最新资源
- 共享存储可重构计算机软硬件通信的优化实现措施和途径.docx
- 个人商用网站大学设计.doc
- 《数据库技术》课程设计报告.doc
- 推进文化产业繁荣与互联网融合发展.docx
- 四工位组合机床的plc控制系统设计---正文.doc
- 计算机三级网络技术考试要点.doc
- 低轨无拖曳卫星的自适应神经网络控制器设计.docx
- java程序方案设计书综合实训实施方案书.doc
- 基于51单片机的酒精检测仪课程方案设计书.doc
- 互联网金融时代下余额宝的风险及监管对策.docx
- 中医中毒MicrosoftPowerPoint演示文稿.ppt
- 第四章作业微型计算机控制技术.ppt
- 项目管理之指定分包商问题.docx
- 关于中职学校计算机实验室的管理与维护的探讨.docx
- 基于Web图书管理系统设计方案与开发.doc
- 企业财务管理信息化中智能预算管理系统研究.docx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈



- 1
- 2
- 3
前往页