- #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 5 /*声明三个信号量ID*/
- int fullid;
- int emptyid;
- int mutxid;
- int main(){
- struct sembuf P,V;
- union semun arg;
- int *array;
- int *sum;
- int *set;
- int *get;
- array=(
拥有帝国一切,皆有可能。欢迎访问phome.netint *)shmat(shmget(IPC_PRIVATE,sizeof(int)*MAXSEM,IPC_CREAT|0666),0,0);
- sum=(int *)shmat(shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666),0,0);
- set=(int *)shmat(shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666),0,0);
- get=(int *)shmat(shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666),0,0);
- *get=0;
-
- fullid=semget(IPC_PRIVATE,0666|IPC_CREAT);
- emptyid=semget(IPC_PRIVATE,0666|IPC_CREAT);
- mutxid=semget(IPC_PRIVATE,0666|IPC_CREAT);
- 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");
拥有帝国一切,皆有可能。欢迎访问phome.net
- arg.val=1;
- if(semctl(mutxid,0,SETVAL,arg)==-1)
- perror("semctl setval error");
- P.sem_num=0;
- P.sem_op=-1;
- P.sem_flg=SEM_UNDO;
- V.sem_num=0;
- V.sem_op=1;
- V.sem_flg=SEM_UNDO;
- if(fork()==0){
- int i=0;
- *set=0;
- while(i<100){
- semop(emptyid,&P,1);
- semop(mutxid,&P,1);
- array[(*set)%MAXSEM]=i 1;
- (*set) ;
- semop(mutxid,&V,1);
- semop(fullid,&V,1);
- i ; }
- sleep(3);
- printf("生产者结束\n");
-
拥有帝国一切,皆有可能。欢迎访问phome.net exit(0);
- }else{
- if(fork()==0){ while(1){
- semop(fullid,&P,1);
- semop(mutxid,&P,1);
- if(*get==100)
- break;
- *sum =array[(*get)%MAXSEM];
- printf("The ConmsumerA Get Number %d\n",array[(*get)%MAXSEM]);
- (*get) ;
- if(get==100)
- printf("The sum is %d\n",sum);
- semop(mutxid,&V,1);
- semop(emptyid,&V,1);
- sleep(1); }
- printf("消费者结束\n");
- exit(0); }else{
- if
|