Lab4 Process Synchronisation – semaphore Cooker and Waiter

advertisement
Lab4
Process Synchronisation – semaphore
Cooker and Waiter
The following two programs, cooker and waiter, show the necessity of process synchronisation. The
cooker program will make one pizza per second and put that pizza onto the shelf (shared memory)
and continue to do this ten times. The waiter program also works for ten seconds and after one
or two seconds (random) will pick one pizza from the shelf. Since there is no synchronisation
between these two processes, and since the waiter process picks up a pizza less often than the
cooker makes the pizza, some pizza is left over.
You are to add a process synchronisation mechanism to both cooker.c and waiter.c, using semaphores
(modified version are cooker s.c and waiter s.c respectively) so that customers can always eat fresh
pizza (cooker follows ”wait until picked up” rule and waiter follows ”wait until made” rule).
cooker.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
main() {
key_t key=STUDENT NUMBER;
int shmid;
int *pizza=0;
int clock=10;
if((shmid=shmget(key,50,0600|IPC_CREAT))==-1) {
perror("shmget");
exit(1);
}
if ((pizza=(int *)shmat(shmid,0,0))==(int *)-1) {
perror("shmat");
exit(2);
}
printf("Cooker: I have started cooking pizza.\n");
while(clock) {
sleep(1);
1
(*pizza)++;
// printf("Cooker: Current pizzas: %d.\n",*pizza);
clock--;
}//end of while
printf("Cooker: Time is up. I cooked 10 pizzas. %d are left.\n"
,*pizza);
shmctl(shmid,IPC_RMID,(struct shmid_ds *) 0);
exit(0);
}//end of main
waiter.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>
main() {
void signal_catcher();
key_t key=STUDENT NUMBER;
int shmid;
int *pizza;
sigset(SIGALRM,signal_catcher);
alarm(10); //set a timer (10 seconds)
if((shmid=shmget(key,50,IPC_CREAT|0600))==-1) {
perror("shmget");
exit(1);
}
if((pizza=(int *)shmat(shmid,0,0))==(int *)-1) {
perror("shmat");
exit(2);
}
while(1){
sleep(rand()%2+1);
(*pizza)--;
}
}//End of main
void signal_catcher() {
exit(0);
}
2
Download