forked from avsm/ipc-bench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shm.c
103 lines (81 loc) · 1.8 KB
/
shm.c
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
/* Measure latency of IPC using shm */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(void)
{
int pfds[2];
char c;
int shmid;
key_t key;
struct timespec *shm;
struct timespec start, stop;
int64_t delta;
int64_t max = 0;
int64_t min = INT64_MAX;
int64_t sum = 0;
int64_t count = 0;
/*
* We'll name our shared memory segment
* "5678".
*/
key = 5678;
if (!fork()) {
/*
* Create the segment.
*/
if ((shmid = shmget(key, 100, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (struct timespec*) -1) {
perror("shmat");
exit(1);
}
while (1) {
clock_gettime(CLOCK_MONOTONIC, shm);
usleep(10000);
}
} else {
sleep(1);
/*
* Locate the segment.
*/
if ((shmid = shmget(key, 100, 0666)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (struct timespec *) -1) {
perror("shmat");
exit(1);
}
while (1) {
while ((shm->tv_sec == start.tv_sec) && (shm->tv_nsec == start.tv_nsec)) {}
clock_gettime(CLOCK_MONOTONIC, &stop);
start = *shm;
delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1000000000 +
stop.tv_nsec - start.tv_nsec);
if (delta > max)
max = delta;
else if (delta < min)
min = delta;
sum += delta;
count++;
if (!(count % 100)) {
printf("%lli %lli %lli\n", max, min, sum / count);
}
}
}
return 0;
}