-
Notifications
You must be signed in to change notification settings - Fork 0
/
Shared_memory.cc
85 lines (65 loc) · 1.96 KB
/
Shared_memory.cc
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
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "Shared_memory.h"
static int getSharedBlock(char * fileName, int size, unsigned int proj_id) {
key_t key;
// Request a key and link it to a filename
key = ftok(fileName, proj_id);
if (key == IPC_ERROR) {
return IPC_ERROR;
}
// Create block or get it if it exists
return shmget(key, size, IPC_CREAT | 0644);
}
message * attachBlock(char * fileName, int size, unsigned int proj_id) {
message * result;
// Request the shared block id
int sharedBlockId = getSharedBlock(fileName, size, proj_id);
if (sharedBlockId == IPC_ERROR)
return NULL;
// Map the shared block to the current proccess
// and return a pointer to it
result = (message *) shmat(sharedBlockId, NULL, 0);
if (result == (message*)IPC_ERROR) {
return NULL;
}
return result;
}
bool * attachFlagBlock(char * fileName, int size, unsigned int proj_id) {
bool * result;
// Request the shared block id
int sharedBlockId = getSharedBlock(fileName, size, proj_id);
if (sharedBlockId == IPC_ERROR)
return NULL;
/*
Map the shared block to the current proccess
and return a pointer to it
*/
result = (bool *)shmat(sharedBlockId, NULL, 0);
if (result == (bool *)IPC_ERROR) {
return NULL;
}
return result;
}
bool detachBlock(message * block) {
return (shmdt(block) != IPC_ERROR);
}
bool detachBlock(bool *block) {
return (shmdt(block) != IPC_ERROR);
}
bool destroyBlock(char * fileName, int size, unsigned int proj_id) {
int sharedBlockId = getSharedBlock(fileName, size, proj_id);
if (sharedBlockId == IPC_ERROR) {
return NULL;
}
return(shmctl(sharedBlockId, IPC_RMID, NULL) != IPC_ERROR);
}
bool destroyBlock(char *fileName, unsigned int proj_id) {
int sharedBlockId = getSharedBlock(fileName, sizeof(bool *), proj_id);
if (sharedBlockId == IPC_ERROR) {
return NULL;
}
return (shmctl(sharedBlockId, IPC_RMID, NULL) != IPC_ERROR);
}