62 lines
1.6 KiB
C
62 lines
1.6 KiB
C
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <sys/shm.h>
|
|
#include <unistd.h>
|
|
#include "shared.h"
|
|
|
|
void StartConsumer(SharedStruct* sharedMem);
|
|
void Consume(SharedStruct* sharedMem);
|
|
void consume_item(int item, SharedStruct* sharedMem);
|
|
int remove_item(SharedStruct* sharedMem);
|
|
|
|
// Checks for SharedID, then begins producing numbers into shared memory.
|
|
int main(int argc, char* argv[])
|
|
{
|
|
if (argc != 2)
|
|
{
|
|
fprintf(stderr, "Usage: %s SharedID# \n", argv[0]);
|
|
exit(1);
|
|
}
|
|
int sharedID = StringToNumber(argv[1]);
|
|
SharedStruct* sharedMem = shmat(sharedID, NULL, 0);
|
|
StartConsumer(sharedMem);
|
|
return 0;
|
|
}
|
|
|
|
// Starts the consumer process.
|
|
void StartConsumer(SharedStruct* sharedMem)
|
|
{
|
|
for (int i = 0; i < 5; i++)
|
|
{
|
|
sem_wait(&sharedMem->full);
|
|
Consume(sharedMem);
|
|
sem_post(&sharedMem->empty);
|
|
}
|
|
}
|
|
|
|
// Takes a number from the shared memory and consumes it.
|
|
void Consume(SharedStruct* sharedMem)
|
|
{
|
|
int consumeNum;
|
|
sem_wait(&sharedMem->mutex);
|
|
consumeNum = remove_item(sharedMem);
|
|
consume_item(consumeNum, sharedMem);
|
|
printf("%d was consumed.\n", consumeNum);
|
|
sem_post(&sharedMem->mutex);
|
|
return;
|
|
}
|
|
|
|
// Increments the count of numbers generated so far in shared memory.
|
|
void consume_item(int item, SharedStruct* sharedMem)
|
|
{
|
|
sharedMem->count[item]++;
|
|
return;
|
|
}
|
|
|
|
// Take item out of shared memory.
|
|
int remove_item(SharedStruct* sharedMem)
|
|
{
|
|
int item = sharedMem->buffer[0];
|
|
sharedMem->buffer[0] = -1;
|
|
return item;
|
|
} |