Codings:
Producer.c
#include<stdio.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<stdlib.h>
main()
{
int *data,shmid,semid,pid,i;
shmid=shmget(1234,1,0666|IPC_CREAT);
semid=semget(1234,1,0666|IPC_CREAT);
data=(int*)shmat(shmid,0,0);
for(i=1;i<=5;i++)
{
printf("\n Producer entering critical stage\n");
struct sembuf *sbuf=(struct sembuf*)malloc(sizeof(struct sembuf));
sbuf->sem_num=0;
sbuf->sem_op=1;
sbuf->sem_flg=0;
printf("\n Enter The Data To Be Produced\n");
scanf("%d",data);
printf("\nProducer exiting the critical region\n");
semop(semid,sbuf,1);
}
}
Consumer.c
#include<stdio.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<sys/types.h>
#include<stdlib.h>
main()
{
int *data,shmid,semid,pid,i,d1,val=0;
shmid=shmget(1234,1,0666|IPC_CREAT);
semid=semget(1234,1,0666|IPC_CREAT);
data=(int*)shmat(shmid,0,0);
for(i=1;i<=5;i++)
{
struct sembuf *sbuf=(struct sembuf*)malloc(sizeof(struct sembuf));
sbuf->sem_num=0;
sbuf->sem_op=1;
sbuf->sem_flg=0;
printf("\n Consumer Waiting \n");
semop(semid,sbuf,1);
printf("\nConsumer Entering The Critical Region\n");
printf("\n Enter The Consumer Values\n");
scanf("%d",&d1);
*data=*data+val;
if(d1<=*data)
{
val=*data-d1;
printf("\n Data Consumed %d ",d1);
printf("\n Remaining data %d ",val);
}
else
{
printf("\n Consumer value exceeds producer values\n");
printf("\n Consumer Exiting the Critical Region\n");
}
}
semctl(semid,IPC_RMID,0);
shmdt(data);
shmctl(shmid,IPC_RMID,0);
}
Ouptut:
[telnet50@linux ~]$ cc producer.c
[telnet50@linux ~]$ ./a.out
Producer entering critical stage
Enter The Data To Be Produced
10
Producer exiting the critical region
Producer entering critical stage
Enter The Data To Be Produced
2
Producer exiting the critical region
Producer entering critical stage
Enter The Data To Be Produced
4
Producer exiting the critical region
Producer entering critical stage
Enter The Data To Be Produced
0
Producer exiting the critical region
Producer entering critical stage
Enter The Data To Be Produced
1
Producer exiting the critical region
[telnet50@linux ~]$ cc consumer.c
[telnet50@linux ~]$ ./a.out
Consumer Waiting
Consumer Entering The Critical Region
Enter The Consumer Values
5
Data Consumed 5
Remaining data 5
Consumer Waiting
Consumer Entering The Critical Region
Enter The Consumer Values
5
Data Consumed 5
Remaining data 2
Consumer Waiting
Consumer Entering The Critical Region
Enter The Consumer Values
3
Data Consumed 3
Remaining data 3
Consumer Waiting
Consumer Entering The Critical Region
Enter The Consumer Values
3
Data Consumed 3
Remaining data 0
Consumer Waiting
Consumer Entering The Critical Region
Enter The Consumer Values
1
Data Consumed 1
Remaining data 0
No comments:
Post a Comment