This repository was archived by the owner on Dec 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshmem.cc
More file actions
93 lines (75 loc) · 1.76 KB
/
shmem.cc
File metadata and controls
93 lines (75 loc) · 1.76 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
#include "shmem.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHMEM_KEY1 425678
int* first_is_new = NULL;
#define SHMEM_KEY2 425679
movement* first = NULL;
#define SHMEM_KEY3 425680
movement* second = NULL;
void shmem_init(bool init_move) {
int shmid;
//Create the segment.
if ((shmid = shmget(SHMEM_KEY1, sizeof(int), IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
//Now we attach the segment to our data space.
if ((first_is_new = (int*)shmat(shmid, NULL, 0)) == (int*) -1) {
perror("shmat");
exit(1);
}
//Create the segment.
if ((shmid = shmget(SHMEM_KEY2, sizeof(movement), IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
//Now we attach the segment to our data space.
if ((first = (movement*)shmat(shmid, NULL, 0)) == (movement*) -1) {
perror("shmat");
exit(1);
}
//Create the segment.
if ((shmid = shmget(SHMEM_KEY3, sizeof(movement), IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
//Now we attach the segment to our data space.
if ((second = (movement*)shmat(shmid, NULL, 0)) == (movement*) -1) {
perror("shmat");
exit(1);
}
if(init_move) {
*first = movement(0,0,0,0);
*first_is_new = true;
}
}
movement shmem_get() {
if(first_is_new == NULL) {
cout<<"Use shmem_init() before shmem_get()."<<endl;
exit(1);
}
if(*first_is_new) {
return *first;
} else {
return *second;
}
}
void shmem_set(movement& m) {
if(first_is_new == NULL) {
cout<<"Use shmem_init() before shmem_set()."<<endl;
exit(1);
}
if(*first_is_new) {
*second = m;
//first_is_new = false;
(void)__sync_fetch_and_and(first_is_new, 0);
} else {
*first = m;
//shm->first_is_new = false;
(void)__sync_fetch_and_or(first_is_new, 1);
}
}