forked from bo-yang/shm_ring_buffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_shmringbuffer.cc
92 lines (84 loc) · 2.41 KB
/
test_shmringbuffer.cc
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
#include "shmringbuffer.hh"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <sched.h>
#include <sys/wait.h>
#include <unistd.h>
struct LogNode {
int ts; // 0 for child; 1 for parent
int len; // length
#define MAX_LOG_LEN 256
char log[MAX_LOG_LEN];
const std::string unparse() {
return "[" + std::to_string(ts) + "] " + std::string(&log[0]);
}
};
int main() {
/* initialize random seed: */
srand(time(NULL));
const int CAPACITY = 20;
pid_t pid1 = fork();
pid_t wpid;
if (pid1 == 0) {
// child process must start after master process
usleep(5000);
ShmRingBuffer<LogNode> buffer(CAPACITY, false);
int start = 1000;
LogNode log;
log.ts = 0;
for (int i = start; i < start + 10 * CAPACITY; ++i) {
snprintf(log.log, MAX_LOG_LEN, "%zu: %d", buffer.end(), i);
buffer.push_back(log);
std::cout << "child: insert " << i << ", index " << buffer.end()
<< "; count: " << buffer.count() << std::endl; // FIXME
usleep(rand() % 1000 + 500);
}
exit(0);
} else if (pid1 > 0) {
pid_t pid2 = fork();
if (pid2 == 0) {
// Child2, reading
usleep(5000);
ShmRingBuffer<LogNode> buffer(CAPACITY, false);
LogNode tmp;
int cnt{0};
while (buffer.pop_front(tmp)) {
std::cout << "pop_ front: " << string(tmp.unparse()) << std::endl;
cnt++;
usleep(rand() % 900 + 500);
}
std::cout << "Child2: popped " << cnt << " logs." << std::endl;
exit(0);
} else if (pid2 > 0) {
// parent process
ShmRingBuffer<LogNode> buffer(CAPACITY, true);
int start = 2000;
LogNode log;
log.ts = 1;
for (int i = start; i < start + 10 * CAPACITY; ++i) {
snprintf(log.log, MAX_LOG_LEN, "%zu: %d", buffer.end(), i);
buffer.push_back(log);
std::cout << "parent: insert " << i << ", index " << buffer.end()
<< "; count: " << buffer.count() << std::endl; // FIXME
usleep(rand() % 900 + 500);
}
int status;
while ((wpid = wait(&status)) > 0)
;
std::cout << "Ring Buffer:" << std::endl;
std::cout << buffer.unparse() << std::endl;
} else {
// fork failed
std::cout << "fork() failed." << std::endl;
return 1;
}
} else {
// fork failed
std::cout << "fork() failed." << std::endl;
return 1;
}
return 0;
}