-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsumer.c
More file actions
53 lines (46 loc) · 1.12 KB
/
consumer.c
File metadata and controls
53 lines (46 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <signal.h>
typedef struct
{
int number;
char data[256];
} Frame;
void sig_handler()
{
shm_unlink("/shm_buffer");
sem_unlink("/shm_empty");
sem_unlink("/shm_data");
}
int main(void)
{
int fd = shm_open("/shm_buffer", O_RDONLY, 0666);
if (fd == -1)
{
printf("error: cant open the shm buffer");
}
sem_t *empty_sem = sem_open("/shm_empty", 0);
sem_t *sem = sem_open("/shm_data", 0);
Frame *frame = mmap(NULL, sizeof(Frame), PROT_READ, MAP_SHARED, fd, 0);
close(fd);
signal(SIGINT, sig_handler);
int frame_num = 0;
sem_post(empty_sem);
while (frame_num < 100)
{
sem_wait(sem); // blocks until the producer signals
printf("Consumer read frame %d: %s\n", frame->number, frame->data);
frame_num = frame->number;
sem_post(empty_sem);
}
munmap(frame, sizeof(Frame));
shm_unlink("/shm_buffer");
sem_unlink("/shm_empty");
sem_unlink("/shm_data");
return 0;
}