shared_mem.cc 2.28 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*!
 *  Copyright (c) 2019 by Contributors
 * \file shared_mem.cc
 * \brief Shared memory management.
 */
#ifndef _WIN32
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <string.h>
#include <dmlc/logging.h>
#include <dgl/runtime/shared_mem.h>

namespace dgl {
namespace runtime {

SharedMemory::SharedMemory(const std::string &name) {
20
#ifndef _WIN32
21
22
23
24
25
  this->name = name;
  this->own = false;
  this->fd = -1;
  this->ptr = nullptr;
  this->size = 0;
26
27
28
#else
  LOG(FATAL) << "Shared memory is not supported on Windows.";
#endif  // _WIN32
29
30
31
}

SharedMemory::~SharedMemory() {
32
#ifndef _WIN32
33
34
35
36
37
38
  munmap(ptr, size);
  close(fd);
  if (own) {
    LOG(INFO) << "remove " << name << " for shared memory";
    shm_unlink(name.c_str());
  }
39
40
41
#else
  LOG(FATAL) << "Shared memory is not supported on Windows.";
#endif  // _WIN32
42
43
}

44
void *SharedMemory::CreateNew(size_t size) {
45
#ifndef _WIN32
46
47
  this->own = true;

48
  int flag = O_RDWR|O_CREAT;
49
50
51
52
53
54
55
56
57
  fd = shm_open(name.c_str(), flag, S_IRUSR | S_IWUSR);
  CHECK_NE(fd, -1) << "fail to open " << name << ": " << strerror(errno);
  auto res = ftruncate(fd, size);
  CHECK_NE(res, -1)
      << "Failed to truncate the file. " << strerror(errno);
  ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  CHECK_NE(ptr, MAP_FAILED)
      << "Failed to map shared memory. mmap failed with error " << strerror(errno);
  return ptr;
58
59
60
#else
  LOG(FATAL) << "Shared memory is not supported on Windows.";
#endif  // _WIN32
61
62
}

63
void *SharedMemory::Open(size_t size) {
64
#ifndef _WIN32
65
66
67
68
69
70
71
  int flag = O_RDWR;
  fd = shm_open(name.c_str(), flag, S_IRUSR | S_IWUSR);
  CHECK_NE(fd, -1) << "fail to open " << name << ": " << strerror(errno);
  ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  CHECK_NE(ptr, MAP_FAILED)
      << "Failed to map shared memory. mmap failed with error " << strerror(errno);
  return ptr;
72
73
74
#else
  LOG(FATAL) << "Shared memory is not supported on Windows.";
#endif  // _WIN32
75
}
76
77

bool SharedMemory::Exist(const std::string &name) {
78
#ifndef _WIN32
79
80
81
82
83
84
85
  int fd = shm_open(name.c_str(), O_RDONLY, S_IRUSR | S_IWUSR);
  if (fd >= 0) {
    close(fd);
    return true;
  } else {
    return false;
  }
86
87
#else
  LOG(FATAL) << "Shared memory is not supported on Windows.";
88
#endif  // _WIN32
89
}
90
91
92

}  // namespace runtime
}  // namespace dgl