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