-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshm.cc
More file actions
39 lines (32 loc) · 1.15 KB
/
Copy pathshm.cc
File metadata and controls
39 lines (32 loc) · 1.15 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
#include "shm.hh"
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
const char* const SHM_NAME = "simple-sc-instance-data";
bool shm_handle_exists() { return shm_get_other_instance_pid() != 0; }
pid_t shm_get_other_instance_pid() {
int fd = shm_open(SHM_NAME, O_RDWR, 0666);
if (fd >= 0) {
ftruncate(fd, sizeof(SharedMemory));
auto ptr = (SharedMemory*)mmap(nullptr, sizeof(SharedMemory), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
return ptr->pid;
}
return 0;
}
SharedMemory* shm_create_handle_with_pid() {
int fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666);
if (fd >= 0) {
ftruncate(fd, sizeof(SharedMemory));
} else {
// We failed to create here so lets try not to create and instead open the already existing.
shm_unlink(SHM_NAME);
fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666);
if (fd >= 0) {
ftruncate(fd, sizeof(SharedMemory));
}
}
auto ptr = (SharedMemory*)mmap(nullptr, sizeof(SharedMemory), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
ptr->pid = getpid();
return ptr;
}
void shm_delete_handle() { shm_unlink(SHM_NAME); }