大连理工大学软件学院操作系统上机实验之生产者与消费者问题(共3页).docx
精选优质文档-倾情为你奉上#include <sys/mman.h>#include <sys/types.h>#include <linux/sem.h>#include <fcntl.h>#include <unistd.h>#include <stdio.h>#include <errno.h>#include <time.h>#define MAXSEM 5int fullid;int emptyid;int mutxid;int main() struct sembuf P,V; union semun agc; int *array; int *sum; int *set; int *get; array=(int*)mmap(NULL,sizeof(int)*5,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0); sum=(int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0); get=(int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0); set=(int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0); *sum=0; *get=0; *set=0; fullid=semget(IPC_PRIVATE,1,IPC_CREAT|00666); emptyid=semget(IPC_PRIVATE,1,IPC_CREAT|00666); mutxid=semget(IPC_PRIVATE,1,IPC_CREAT|00666); agc.val=0; if(semctl(fullid,0,SETVAL,agc)=-1) perror("semctl semval error"); agc.val=MAXSEM; if(semctl(emptyid,0,SETVAL,agc)=-1) perror("semctl setval error"); agc.val=1; if(semctl(mutxid,0,SETVAL,agc)=-1) perror("semctl semval error"); V.sem_num=0; V.sem_op=1; V.sem_flg=SEM_UNDO; P.sem_num=0; P.sem_op=-1; P.sem_flg=SEM_UNDO; if(fork()=0) int i=0; while(i<20) semop(emptyid,&P,1); semop(mutxid,&P,1); array*(set)%MAXSEM=i+1; printf("Producer %dn",array(*set)%MAXSEM); (*set)+; semop(mutxid,&V,1); semop(fullid,&V,1); i+; sleep(10); printf("Producer is over"); exit(0); else if(fork()=0) while(1) semop(fullid,&P,1); semop(mutxid,&P,1); if(*get=20) break; *sum+=array(*get)%MAXSEM; printf("The ConsumerA Get Number %dn",array(*get)%MAXSEM); (*get)+; if(*get=20) printf("The sum is %dn",*sum); semop(mutxid,&V,1); semop(emptyid,&V,1); sleep(1); printf("ConsumerA is over"); exit(0); else if(fork()=0) while(1) semop(fullid,&P,1); semop(mutxid,&P,1); if(*get=20) break; *sum+=array(*get)%MAXSEM; printf("The ConsumerB Get Number %dn",array(*get)%MAXSEM); (*get)+; if(*get=20) printf("The sum is %dn",*sum); semop(mutxid,&V,1); semop(emptyid,&V,1); sleep(1); printf("ConsumerB is over"); exit(0); return 0; 专心-专注-专业