-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathring_logger_shm.c
More file actions
111 lines (102 loc) · 2.67 KB
/
Copy pathring_logger_shm.c
File metadata and controls
111 lines (102 loc) · 2.67 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
#define SLOT_MSG 64
#define SLOTS 64
typedef struct {
atomic_uint_fast64_t seq;
char msg[SLOT_MSG];
} slot_t;
typedef struct {
slot_t slots[SLOTS];
} ring_t;
static ring_t *ring_create(const char *name)
{
int fd = shm_open(name, O_CREAT | O_RDWR, 0600);
if (fd < 0) return NULL;
if (ftruncate(fd, sizeof(ring_t)) < 0) {
close(fd);
return NULL;
}
void *p = mmap(NULL, sizeof(ring_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
if (p == MAP_FAILED) return NULL;
ring_t *r = p;
for (int i = 0; i < SLOTS; i++) {
atomic_store_explicit(&r->slots[i].seq, 0, memory_order_relaxed);
r->slots[i].msg[0] = 0;
}
return r;
}
static ring_t *ring_open(const char *name)
{
int fd = shm_open(name, O_RDWR, 0);
if (fd < 0) return NULL;
void *p = mmap(NULL, sizeof(ring_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
if (p == MAP_FAILED) return NULL;
return p;
}
static void ring_log(ring_t *r, uint64_t seq, const char *msg)
{
size_t idx = seq % SLOTS;
slot_t *s = &r->slots[idx];
atomic_store_explicit(&s->seq, seq, memory_order_release);
snprintf(s->msg, SLOT_MSG, "%s", msg);
}
static void writer_proc(const char *name)
{
ring_t *r = ring_open(name);
if (!r) _exit(1);
for (uint64_t i = 1; i <= 100; i++) {
char buf[64];
snprintf(buf, sizeof buf, "log-%llu", (unsigned long long)i);
ring_log(r, i, buf);
usleep(10000);
}
_exit(0);
}
static void reader_proc(const char *name)
{
ring_t *r = ring_open(name);
if (!r) _exit(1);
uint64_t last = 0;
for (;;) {
int seen = 0;
for (int i = 0; i < SLOTS; i++) {
uint64_t seq = atomic_load_explicit(&r->slots[i].seq, memory_order_acquire);
if (seq > last) {
printf("seq=%llu msg=%s\n", (unsigned long long)seq, r->slots[i].msg);
if (seq > last) last = seq;
seen = 1;
}
}
if (!seen && last >= 100) break;
usleep(20000);
}
_exit(0);
}
int main(void)
{
const char *name = "/ring_logger_example";
shm_unlink(name);
ring_t *r = ring_create(name);
if (!r) return 1;
pid_t w = fork();
if (w == 0) writer_proc(name);
pid_t rpid = fork();
if (rpid == 0) reader_proc(name);
waitpid(w, NULL, 0);
waitpid(rpid, NULL, 0);
shm_unlink(name);
return 0;
}