Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

# PROGRAM 10-Implement the solution to the producer-consumer

problem
using semaphores.
CODE & OUTPUT :
producer:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<stdio.h>
#include<stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<stdbool.h>
#include <sys/ipc.h>
#include <sys/shm.h>
void wait1(int semid, int semnum){
struct sembuf semoparray[1];
semoparray[0].sem_num=semnum;
semoparray[0].sem_op=-1;
semoparray[0].sem_flg=0;
semop(semid, semoparray, 1);
}
void signal1(int semid, int semnum){
struct sembuf semoparray[1];
semoparray[0].sem_num=semnum;
semoparray[0].sem_op=1;
semoparray[0].sem_flg=0;
semop(semid, semoparray, 1);
}
struct buffer
{
char buff[4][100];
int count;
};
int main(void){
key_t semKey = 1000,bufkey=255;
int semId,semval,shmid,in;
struct buffer *buf;
semId=semget(semKey, 1, IPC_CREAT);
if(semId==-1){
printf("Could not create semaphore \n");
exit(0);
}
shmid=shmget(bufkey,sizeof(struct buffer),IPC_CREAT|0666);
if(shmid==-1)
{
printf("Can't create shared memory.\n");
exit(0);
}
buf=(struct buffer*)shmat(shmid,NULL,0);
in=0;
while(1){
while(buf->count==4);
{
printf("Enter something:\n");
scanf("%s",buf->buff[in]);
in=(in+1)%4;
}
wait1(semId,0);
buf->count++;
signal1(semId,0);
}
}
Producer Output:
Enter something:
Hello
Enter something:
world
Consumer program:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<stdio.h>
#include<stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<stdbool.h>
#include <sys/ipc.h>
#include <sys/shm.h>
void wait1(int semid, int semnum){
struct sembuf semoparray[1];
semoparray[0].sem_num=semnum;
semoparray[0].sem_op=-1;
semoparray[0].sem_flg=0;
semop(semid, semoparray, 1);
}
void signal1(int semid, int semnum){
struct sembuf semoparray[1];
semoparray[0].sem_num=semnum;
semoparray[0].sem_op=1;
semoparray[0].sem_flg=0;
semop(semid, semoparray, 1);
}
struct buffer
{
char buff[4][100];
int count;
};
int main(void){
key_t semKey = 1000,bufkey=255;
int semId,semval,shmid,out;
struct buffer *buf;
semId=semget(semKey, 1, IPC_CREAT);
if(semId==-1){
printf("Could not create semaphore \n");
exit(0);
}
shmid=shmget(bufkey,sizeof(struct buffer),IPC_CREAT|0666);
if(shmid==-1)
{
printf("Can't create shared memory.\n");
exit(0);
}
buf=(struct buffer*)shmat(shmid,NULL,0);
out=0;
while(1){
while(buf->count==0);
printf("The string from consumer:%s\n",buf->buff[out]);
sleep(10);
out=(out+1)%4;
wait1(semId, 0);
buf->count--;
signal1(semId, 0);
}
}
consumer output:
The string from consumer:Hello
The string from consumer:world

You might also like