OS LAB 8
Name:Vedant Choudhari
Reg.no. :22BCE1636
Producer Consumer Problem:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <semaphore.h>
int main() {
const char *memName = "shared_memory";
int shm_fd = shm_open(memName, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, sizeof(int));
int *buffer = mmap(0, sizeof(int), PROT_READ | PROT_WRITE,
MAP_SHARED, shm_fd, 0);
sem_t *empty = sem_open("empty_semaphore", O_CREAT, 0644, 1);
sem_t *full = sem_open("full_semaphore", O_CREAT, 0644, 0);
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) { // Child process (Consumer)
for (int i = 0; i < 5; ++i) {
sem_wait(full); // Wait until there is at least one item produced
printf("Consumer consumed: %d\n", *buffer);
sem_post(empty); // Indicate one item consumed
}
exit(EXIT_SUCCESS);
} else { // Parent process (Producer)
for (int i = 0; i < 5; ++i) {
sem_wait(empty); // Wait until there is at least one empty slot
*buffer = i;
printf("Producer produced: %d\n", i);
sem_post(full); // Indicate one slot is now filled
}
}
return 0;
}
OUTPUT
DINING PHILOSOPHER
Code:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#define NUM_PHILOSOPHERS 5
sem_t forks[NUM_PHILOSOPHERS];
void* philosopher(void* num);
int main() {
pthread_t philosophers[NUM_PHILOSOPHERS];
int philosopher_numbers[NUM_PHILOSOPHERS];
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
sem_init(&forks[i], 0, 1);
}
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
philosopher_numbers[i] = i;
pthread_create(&philosophers[i], NULL, philosopher,
&philosopher_numbers[i]);
}
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
pthread_join(philosophers[i], NULL);
}
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
sem_destroy(&forks[i]);
}
return 0;
}
void* philosopher(void* num) {
int philosopher_number = *(int*)num;
while (1) {
printf("Philosopher %d is thinking.\n", philosopher_number);
sem_wait(&forks[philosopher_number]);
printf("Philosopher %d picked up left fork.\n", philosopher_number);
sem_wait(&forks[(philosopher_number + 1) %
NUM_PHILOSOPHERS]);
printf("Philosopher %d picked up right fork - now eating.\n",
philosopher_number);
sleep(1);
sem_post(&forks[(philosopher_number + 1) %
NUM_PHILOSOPHERS]);
sem_post(&forks[philosopher_number]);
printf("Philosopher %d put down both forks - now thinking.\n",
philosopher_number);
}
}
OUTPUT