-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsharedmemory.cpp
63 lines (51 loc) · 1.58 KB
/
sharedmemory.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
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <cstring>
#include "sharedmemory.h"
#include "logger.h"
const std::string sharedMemoryFile("/cefbrowser");
const size_t sharedMemorySize = 3840 * 2160 * 4; // 4K
SharedMemory::SharedMemory() {
int shmid = shm_open(sharedMemoryFile.c_str(), O_RDWR, 0666);
if (shmid < 0) {
mode_t old_umask = umask(0);
shmid = shm_open(sharedMemoryFile.c_str(), O_EXCL | O_CREAT | O_RDWR, 0666);
umask(old_umask);
if (shmid >= 0) {
ftruncate(shmid, sharedMemorySize);
} else if (errno == EEXIST) {
shmid = shm_open(sharedMemoryFile.c_str(), O_RDWR, 0666);
}
}
if (shmid < 0) {
CRITICAL("Could not open shared memory (shm_open): {}", strerror(errno));
exit(1);
}
shmp = (uint8_t*)mmap(nullptr, sharedMemorySize, PROT_READ | PROT_WRITE, MAP_SHARED, shmid, 0);
if (shmp == MAP_FAILED) {
CRITICAL("Could not open shared memory (mmap): {}", strerror(errno));
exit(1);
}
close(shmid);
}
SharedMemory::~SharedMemory() {
munmap(shmp, sharedMemorySize);
shm_unlink(sharedMemoryFile.c_str());
}
uint8_t* SharedMemory::Get() {
return shmp;
}
bool SharedMemory::Write(uint8_t* data, size_t size) {
if (size > sharedMemorySize || size <= 0) {
// abort
ERROR("Prevent writing %d bytes in buffer of length %d", size, sharedMemorySize);
return false;
}
memcpy(shmp, data, size);
return true;
}
void SharedMemory::Clear() {
memset(shmp, 0, sharedMemorySize);
}