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
112
113
114
115
116
117
118
119
120
121
122
123
124
|
#ifdef _WIN32
int main() {
return 0;
}
#else
# include "../kit/threads.h"
# include <stdio.h>
# include <string.h>
# include <sys/mman.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
# define NAME "/kit_test_interprocess"
enum { STATE_INIT, STATE_READY, STATE_DONE };
enum { SIZE = 64 };
int run_writer() {
int f = shm_open(NAME, O_RDWR | O_CREAT, 0660);
if (f == -1) {
printf("%s: shm_open failed.\n", __FUNCTION__);
return 1;
}
if (ftruncate(f, SIZE) == -1) {
printf("%s: ftruncate failed.\n", __FUNCTION__);
fflush(stdout);
return 1;
}
void *p = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, f,
0);
if (p == MAP_FAILED) {
printf("%s: mmap failed.\n", __FUNCTION__);
fflush(stdout);
return 1;
}
unsigned char *bytes = (unsigned char *) p;
bytes[0] = STATE_INIT;
for (int i = 1; i < SIZE; i++) bytes[i] = i;
bytes[0] = STATE_READY;
while (bytes[0] != STATE_DONE) thrd_yield();
shm_unlink(NAME);
return 0;
}
int run_reader() {
int f = -1;
while (f == -1) {
f = shm_open(NAME, O_RDWR, 0);
thrd_yield();
}
void *p = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, f,
0);
if (p == MAP_FAILED) {
printf("%s: mmap failed.\n", __FUNCTION__);
fflush(stdout);
return 1;
}
unsigned char *bytes = (unsigned char *) p;
while (bytes[0] != STATE_READY) thrd_yield();
int status = 0;
for (int i = 1; i < SIZE; i++)
if (bytes[i] != i) {
printf("%s: wrong byte %d\n", __FUNCTION__, i);
fflush(stdout);
status = 1;
}
bytes[0] = STATE_DONE;
return status;
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("Wrong number of command line arguments %d\n", argc);
return 1;
}
int status = 0;
struct timespec t0;
timespec_get(&t0, TIME_UTC);
if (strcmp(argv[1], "writer") == 0)
status = run_writer();
else if (strcmp(argv[1], "reader") == 0)
status = run_reader();
else {
printf("Invalid command line argument \"%s\"\n", argv[1]);
return 1;
}
struct timespec t1;
timespec_get(&t1, TIME_UTC);
long long sec = t1.tv_sec - t0.tv_sec;
long long nsec = t1.tv_nsec - t0.tv_nsec;
printf("%s: done in %.2lf msec\n", argv[1],
(sec * 1000000000 + nsec) * 0.000001);
fflush(stdout);
return status;
}
#endif
|