Files
sp-lab/2.c
T
2026-05-14 00:24:19 +05:30

83 lines
1.5 KiB
C

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include<semaphore.h>
struct message{
long type;
int data;
};
int main(){
int n;
printf("How many items to produce? ");
scanf("%d", &n);
int msgid = msgget(IPC_PRIVATE, O_CREAT | 0666);
sem_unlink("/mutex");
sem_unlink("/empty");
sem_unlink("/full");
sem_t *mutex = sem_open("/mutex", O_CREAT, 0644,1);
sem_t *empty = sem_open("/empty", O_CREAT, 0644,n);
sem_t *full = sem_open("/full", O_CREAT, 0644,0);
if(fork() == 0){
struct message msg;
msg.type = 1;
for(int i =1;i<=n;i++){
sem_wait(empty);
sem_wait(mutex);
msg.data = i;
msgsnd(msgid, &msg, sizeof(msg.data), 0);
printf("Produced: %d\n", i);
sem_post(full);
sem_post(mutex);
sleep(1);
}
exit(0);
}
if(fork() == 0){
struct message msg;
for(int i =1;i<=n;i++){
sem_wait(full);
sem_wait(mutex);
msgrcv(msgid, &msg, sizeof(msg.data),1, 0);
printf("Consumed: %d\n", msg.data);
sem_post(empty);
sem_post(mutex);
sleep(2);
}
exit(0);
}
wait(NULL);
wait(NULL);
msgctl(msgid, IPC_RMID, NULL);
sem_unlink("/mutex");
sem_unlink("/empty");
sem_unlink("/full");
printf("\nDOne\n");
return 0;
}