-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMemorySharing.cpp
82 lines (70 loc) · 1.85 KB
/
MemorySharing.cpp
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
#include "MemorySharing.h"
const char* MemorySharer::GETKEYDIR = "/tmp";
MemorySharer::MemorySharer(const ushort projectId, uint shmSize)
{
(this->key) = ftok(MemorySharer::GETKEYDIR, projectId);
if ((this->key) < 0)
ErrExit("ftok error");
(this->shmId) = shmget((this->key), shmSize, IPC_CREAT | IPC_EXCL | 0664);
if ((this->shmId) == -1)
{
if (errno == EEXIST)
{
printf("shared memeory already exist\n");
(this->shmId) = shmget((this->key), 0, 0);
printf("reference shmId = %d\n", (this->shmId));
}
else
{
perror("errno");
ErrExit("shmget error");
}
}
if ((void*)((this->ptr) = (uchar*)shmat((this->shmId), 0, 0)) == (void*)-1)
{
if (shmctl((this->shmId), IPC_RMID, NULL) == -1)
ErrExit("shmctl error");
else
{
printf("Attach shared memory failed\n");
printf("remove shared memory identifier successful\n");
}
ErrExit("shmat error");
}
*ptr = 0;
}
MemorySharer::~MemorySharer(void)
{
if (shmdt(this->ptr) < 0)
ErrExit("shmdt error");
if (shmctl((this->shmId), IPC_RMID, NULL) == -1)
ErrExit("shmctl error");
else
{
printf("Finally\n");
printf("remove shared memory identifier successful\n");
}
}
void MemorySharer::ErrExit(const char* msg)
{
fprintf(stderr, "%s\n", msg);
exit(1);
}
ImageMemorySharer::ImageMemorySharer(const ushort projectId, uint shmSize) : MemorySharer(projectId, shmSize)
{
}
ByteMemorySharer::ByteMemorySharer(const ushort projectId, uint shmSize) : MemorySharer(projectId, shmSize)
{
}
uchar* ImageMemorySharer::getPtr(void)
{
return ptr;
}
uchar ByteMemorySharer::ReadByte(void)
{
return *ptr;
}
void ByteMemorySharer::WriteByte(uchar x)
{
*ptr = x;
}