#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <unistd.h>
#define BUFFER_SIZE 10
typedef struct {
int buffer[BUFFER_SIZE];
int in;
int out;
int count;
} Buffer;
int main() {
int shmid, semid;
key_t key = ftok(".", 'S');
Buffer *buffer;
// Create shared memory
shmid = shmget(key, sizeof(Buffer), IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(1);
}
// Attach shared memory
buffer = (Buffer *)shmat(shmid, NULL, 0);
if (buffer == (Buffer *)(-1)) {
perror("shmat");
exit(1);
}
// Create semaphore set
semid = semget(key, 1, IPC_CREAT | 0666);
if (semid == -1) {
perror("semget");
exit(1);
}
// Initialize semaphore
semctl(semid, 0, SETVAL, 1);
// Open data file
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
perror("fopen");
exit(1);
}
// Produce data
int data;
while (fscanf(file, "%d", &data) == 1) {
// Get mutex semaphore
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = -1;
sem_op.sem_flg = 0;
semop(semid, &sem_op, 1);
// Check if buffer is full
if (buffer->count < BUFFER_SIZE) {
// Insert data
buffer->buffer[buffer->in] = data;
buffer->in = (buffer->in + 1) % BUFFER_SIZE;
buffer->count++;
printf("Produced: %d\n", data);
}
// Release mutex semaphore
sem_op.sem_op = 1;
semop(semid, &sem_op, 1);
// Wait for some time
sleep(1);
}
// Close the file
fclose(file);
// Detach shared memory
shmdt(buffer);
return 0;
}