mirror of
https://github.com/Manoj-HV30/sp-lab.git
synced 2026-05-16 19:35:27 +00:00
cooked
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
#include<stdio.h>
|
||||
#include<stdlib.h>
|
||||
#include<unistd.h>
|
||||
#include<sys/ipc.h>
|
||||
#include<sys/wait.h>
|
||||
#include<semaphore.h>
|
||||
#include<sys/shm.h>
|
||||
#include<fcntl.h>
|
||||
|
||||
#define BUFFER_SIZE 5
|
||||
|
||||
struct shared{
|
||||
int buffer[BUFFER_SIZE];
|
||||
int in;
|
||||
int out;
|
||||
};
|
||||
|
||||
int main(){
|
||||
int n;
|
||||
printf("\nhow many items to produce? ");
|
||||
scanf("%d", &n);
|
||||
|
||||
int shmid = shmget(IPC_PRIVATE, sizeof(struct shared), IPC_CREAT | 0666);
|
||||
struct shared* s = (struct shared* )shmat(shmid, NULL, 0);
|
||||
s->in = 0;
|
||||
s->out = 0;
|
||||
|
||||
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, BUFFER_SIZE);
|
||||
sem_t *full = sem_open("/full", O_CREAT, 0644, 0);
|
||||
|
||||
if(fork()==0){
|
||||
for(int i =1;i<=n;i++){
|
||||
sem_wait(empty);
|
||||
sem_wait(mutex);
|
||||
s->buffer[s->in] = i;
|
||||
printf("produced: %d slot: %d\n", i, s->in);
|
||||
s->in = (s->in+1)%BUFFER_SIZE;
|
||||
|
||||
sem_post(mutex);
|
||||
sem_post(full);
|
||||
sleep(1);
|
||||
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if(fork()==0){
|
||||
for(int i =1;i<=n;i++){
|
||||
sem_wait(full);
|
||||
sem_wait(mutex);
|
||||
int item = s->buffer[s->out];
|
||||
printf("consumed: %d slot: %d\n", item, s->out);
|
||||
s->out = (s->out+1)%BUFFER_SIZE;
|
||||
|
||||
sem_post(mutex);
|
||||
sem_post(empty);
|
||||
sleep(2);
|
||||
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
wait(NULL);
|
||||
wait(NULL);
|
||||
|
||||
shmdt(s);
|
||||
shmctl(shmid, IPC_RMID, NULL);
|
||||
sem_unlink("/mutex");
|
||||
sem_unlink("/empty");
|
||||
sem_unlink("/full");
|
||||
|
||||
return 0;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user