-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_memory.c
61 lines (47 loc) · 1.04 KB
/
shared_memory.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
#include <sys/stat.h>
#include <sys/shm.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "shared_memory.h"
int get_shared_memory() {
int shmemid;
shmemid = shmget(IPC_PRIVATE, getpagesize(), IPC_CREAT | S_IRUSR | S_IWUSR);
if (shmemid == -1) {
perror("shmget");
exit(1);
}
return shmemid;
}
void* attach_to_shared_memory(int shmemid, unsigned int readonly) {
void* p;
int shmflag;
if (readonly) {
shmflag = SHM_RDONLY;
}
else {
shmflag = 0;
}
p = (void*)shmat(shmemid, 0, shmflag);
if (!p) {
perror("shmat");
exit(1);
}
return p;
}
void cleanup_shared_memory(int shmemid, void* p) {
detach_from_shared_memory(p);
deallocate_shared_memory(shmemid);
}
void detach_from_shared_memory(void* p) {
if (shmdt(p) == -1) {
perror("shmdt");
exit(1);
}
}
void deallocate_shared_memory(int shmemid) {
if (shmctl(shmemid, IPC_RMID, 0) == 1) {
perror("shmctl");
exit(1);
}
}