-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_memory.c
More file actions
114 lines (82 loc) · 1.67 KB
/
shared_memory.c
File metadata and controls
114 lines (82 loc) · 1.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
112
113
114
#include "util.h"
#include "shared_memory.h"
/**
*/
unsigned int shmExists(char * key) {
unsigned int result;
char * data;
result = shmFetch(key, &data);
if(result != 0) {
return SHM_ERROR_NOT_FOUND;
}
if(strcmp(data, "") != 0) {
return SHM_ERROR_FOUND;
}
return SHM_ERROR_NOT_FOUND;
}
/**
*/
unsigned int shmStore(char * key, char * data) {
int shm;
size_t len;
char *addr;
len = strlen(data);
if(DEBUG) {
printf("DEBUG: Storing %d bytes of data for key '%s'\n", (int)len, key);
}
shm = shm_open(key, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if(shm == -1) {
return SHM_ERROR_OPEN;
}
ftruncate(shm ,len);
if(shm == -1) {
return SHM_ERROR_TRUNCATE;
}
addr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED , shm, 0);
if(addr == MAP_FAILED) {
close(shm);
return SHM_ERROR_MMAP;
}
close(shm);
if(DEBUG) {
printf("DEBUG: Copying %d bytes data to memory\n", (int)len);
}
memcpy(addr, data, len);
// Don't forget to free the mmapped memory
if (munmap(addr, len) == -1) {
return SHM_ERROR_MUNMAP;
}
return STATUS_SUCCESS;
}
/**
*/
unsigned int shmFetch(char * key, char ** data) {
int shm;
int s;
struct stat f;
shm = shm_open(key, O_RDWR | O_EXCL, 0);
if(shm == -1) {
return SHM_ERROR_OPEN;
}
s = fstat(shm , &f);
if(s == -1) {
return SHM_ERROR_STAT;
}
(*data) = mmap(NULL, f.st_size, PROT_READ | PROT_WRITE, MAP_SHARED , shm, 0);
if((*data) == MAP_FAILED) {
close(shm);
return SHM_ERROR_MMAP;
}
close(shm);
return STATUS_SUCCESS;
}
/**
*/
unsigned int shmDelete(char * key) {
int result;
result = shm_unlink(key);
if(result == -1) {
return SHM_ERROR_DELETE;
}
return STATUS_SUCCESS;
}