#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <unistd.h>
#define SHARED_MEMORY_SIZE 1024
#define BUFFER_SIZE 5
#define EMPTY 0
#define FULL 1
struct sembuf acquire = {0, -1, SEM_UNDO};
struct sembuf release = {0, 1, SEM_UNDO};
struct shared_memory {
int buffer[BUFFER_SIZE];
int status[BUFFER_SIZE];
};
int main() {
key_t key = ftok(".", 'S');
int shmid = shmget(key, sizeof(struct shared_memory), IPC_CREAT | 0666);
int semid = semget(key, 1, IPC_CREAT | 0666);
struct shared_memory *shared_mem = (struct shared_memory *) shmat(shmid, NULL, 0);
for (int i = 0; i < BUFFER_SIZE; i++) {
shared_mem->status[i] = EMPTY;
}
FILE *input_file = fopen("input.txt", "r");
if (input_file == NULL) {
printf("Failed to open input file.\n");
return 1;
}
int item;
int num_items = 0;
while (fscanf(input_file, "%d", &item) == 1) {
sleep(rand() % 3);
semop(semid, &acquire, 1);
int i;
for (i = 0; i < BUFFER_SIZE; i++) {
if (shared_mem->status[i] == EMPTY) {
shared_mem->buffer[i] = item;
shared_mem->status[i] = FULL;
printf("Produced item: %d\n", item);
num_items++;
break;
}
}
semop(semid, &release, 1);
}
fclose(input_file);
printf("Producer completed. Produced %d items.\n", num_items);
shmdt(shared_mem);
shmctl(shmid, IPC_RMID, NULL);
semctl(semid, 0, IPC_RMID);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <unistd.h>
#define SHARED_MEMORY_SIZE 1024
#define BUFFER_SIZE 5
#define EMPTY 0
#define FULL 1
struct sembuf acquire = {0, -1, SEM_UNDO};
struct sembuf release = {0, 1, SEM_UNDO};
struct shared_memory {
int buffer[BUFFER_SIZE];
int status[BUFFER_SIZE];
};
int main() {
key_t key = ftok(".", 'S');
int shmid = shmget(key, sizeof(struct shared_memory), IPC_CREAT | 0666);
int semid = semget(key, 1, IPC_CREAT | 0666);
struct shared_memory *shared_mem = (struct shared_memory *) shmat(shmid, NULL, 0);
FILE *output_file = fopen("output.txt", "w");
if (output_file == NULL) {
printf("Failed to open output file.\n");
return 1;
}
while (1) {
sleep(rand() % 3);
semop(semid, &acquire, 1);
int i;
for (i = 0; i < BUFFER_SIZE; i++) {
if (shared_mem->status[i] == FULL) {
int item = shared_mem->buffer[i];
shared_mem->status[i] = EMPTY;
printf("Consumed item: %d\n", item);
fprintf(output_file, "%d\n", item);
break;
}
}
semop(semid, &release, 1);
}
fclose(output_file);
shmdt(shared_mem);
return 0;
}