Linux进程间的通信,信号量的使用,生产者消费者

这是简单的生产者消费者问题,只有一个缓冲区

#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<linux/sem.h> struct sembuf buf; int Psem(int sem_id); int Vsem(int sem_id); int cache; int main() { union semun arg; int mutexid; int full_sem; int empty_sem; mutexid=semget(IPC_PRIVATE,1,0666|IPC_CREAT); full_sem=semget(IPC_PRIVATE,1,0666|IPC_CREAT); empty_sem=semget(IPC_PRIVATE,1,0666|IPC_CREAT); arg.val=1; if(semctl(mutexid,0,SETVAL,arg)==-1) { perror("set the mutex error/n"); return -1; } arg.val=0; if(semctl(full_sem,0,SETVAL,arg)==-1) { perror("set the full_sem error/n"); return -1; } arg.val=1; if(semctl(empty_sem,0,SETVAL,arg)==-1) { perror("set the empty_sem error/n"); } pid_t pid; pid=fork(); //the father process while(1) { if(pid>0)//the producer { Psem(mutexid); Psem(empty_sem); printf("The producer are producing a product......waiting....."); sleep(1); printf("Done!/n"); Vsem(full_sem); Vsem(mutexid); } else//the consumer { Psem(mutexid); Psem(full_sem); printf("The consumer are consuming a product......waiting......"); sleep(1); printf("Done!/n"); Vsem(empty_sem); Vsem(mutexid); } } return 0; } int Psem(int sem_id) { buf.sem_num=0; buf.sem_op=-1; buf.sem_flg=SEM_UNDO; if(semop(sem_id,&buf,1)==-1) { perror("P failed!/n"); return 0; } return 1; } int Vsem(int sem_id) { buf.sem_num=0; buf.sem_op=1; buf.sem_flg=SEM_UNDO; if(semop(sem_id,&buf,1)==-1) { perror("V failed!/n"); return 0; } return 1; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值