1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include <sys/mman.h> #include <sys/types.h> #include <sys/sem.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <time.h> #include <stdlib.h> #define MAXSEM 5 union semun { int val; struct semid_ds *buf; unsigned short *array; }; int fullid, emptyid,mutxid; int main(){ struct sembuf P,V; union semun arg; int *array; int *sum; int *get; int *set; array =(int *)mmap(NULL,sizeof(int)*MAXSEM,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); set=(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); fullid=semget(IPC_PRIVATE,1,IPC_CREAT|0666); emptyid=semget(IPC_PRIVATE,1,IPC_CREAT|0666); mutxid=semget(IPC_PRIVATE,1,IPC_CREAT|0666); arg.val=0; if(semctl(fullid,0,SETVAL,arg)==-1)perror("semctl setval error"); arg.val=MAXSEM; if(semctl(emptyid,0,SETVAL,arg)==-1)perror("semctl setval error"); arg.val=1; if(semctl(mutxid,0,SETVAL,arg)==-1)perror("semctl setval 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; pid_t fpid1=fork(); if(fpid1==0){ int i=0; while(i<100){ semop(emptyid,&P,1); semop(mutxid,&P,1); array[*(set)%MAXSEM] = i+1; (*set)++; printf("produce %d\n",i+1);
semop(mutxid,&V,1); semop(fullid,&V,1); i++; }
sleep(1);
printf("producer is over\n"); exit(0); }else{ pid_t fpid2=fork(); if(fpid2==0){ while(1){ semop(fullid,&P,1); semop(mutxid,&P,1); if(*get == 100) break; *sum += array[(*get)%MAXSEM]; printf("the comsumer A get number %d\n", array[(*get)%MAXSEM]); (*get) ++; if(*get == 100) {printf("the sum is %d\n", *sum); break; } semop(mutxid,&V,1); semop(emptyid,&V,1); sleep(0.5); } printf("consumer A is over\n"); exit(0); }else{ while(1){ semop(fullid,&P,1); semop(mutxid,&P,1); if(*get == 100) break; *sum += array[(*get)%MAXSEM]; printf("the comsumer B get number %d\n", array[(*get)%MAXSEM]); (*get) ++; if(*get == 100) {printf("the sum is %d\n", *sum); break; } semop(mutxid,&V,1); semop(emptyid,&V,1); sleep(0.5); } printf("consumer B is over\n"); exit(0); } } }
|