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
| #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> union semun{ int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; }arg; int semid; philosopher(int i) { int j; struct sembuf sbuf[2]; sbuf[0].sem_num=i; sbuf[0].sem_flg=SEM_UNDO; sbuf[1].sem_num=(i+1)%5; sbuf[1].sem_flg=SEM_UNDO; for(j=0;j<5;j++) { printf("philosopher %d is thinking\n",i); sleep(2); printf("philosopher %d is hungry\n",i); sbuf[0].sem_op=-1; sbuf[1].sem_op=-1; semop(semid,sbuf,2); printf("philosopher %d is eating\n",i); sleep(2); sbuf[0].sem_op=1; sbuf[1].sem_op=1; semop(semid,sbuf,2); } exit(i); } int main(){ int semid,key,pid,status,i; key=ftok("fname",1); semid=semget(key,5,IPC_CREAT|0666); arg.val=1; for(i=0;i<5;i++) semctl(semid,i,SETVAL,arg); for(i=0;i<5;i++) { pid=fork(); if(pid==0) philosopher(i); } pid=wait(&status); }
|