|
CS471/571 - Operating Systems
|
Displaying ./code/Semaphores/reader.c
#include <stdio.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <fcntl.h>
#define PIPESIZE 10
// Compile: gcc -o reader reader.c -lpthread
struct pipe {
sem_t lock, block;
char data[PIPESIZE];
int wp, rp, initialized;
};
int main(void)
{
int fd = shm_open("/my_pipe", O_RDWR, 0666);
if (fd < 0) {
perror("shm_open");
return 1;
}
struct pipe *pipe = mmap(NULL, sizeof(struct pipe),
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (pipe == MAP_FAILED) {
perror("mmap");
return 1;
}
while (pipe->initialized == 0);
sem_wait(&(pipe->lock));
while(1) {
while (pipe->rp == pipe->wp) {
sem_post(&(pipe->block));
fprintf(stderr,"blocking...\n");
sem_wait(&(pipe->lock));
}
fprintf(stderr, "%c", pipe->data[pipe->rp]);
pipe->rp = (pipe->rp+1) % PIPESIZE;
}
return 0;
}
|