ChimeraTK-DeviceAccess  03.18.00
sharedDummyHelpers.h
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Deutsches Elektronen-Synchrotron DESY, MSK, ChimeraTK Project <chimeratk-support@desy.de>
2 // SPDX-License-Identifier: LGPL-3.0-or-later
3 #pragma once
4 
5 #include <sys/file.h>
6 
7 #include <boost/interprocess/managed_shared_memory.hpp>
8 
9 #include <iostream>
10 #include <string>
11 #include <utility>
12 
13 enum class MirrorRequestType : int { from = 1, to, stop };
14 
15 // Static helper functions
16 std::string createExpectedShmName(std::string instanceId_, std::string mapFileName_, std::string userName) {
17  std::string mapFileHash{std::to_string(std::hash<std::string>{}(mapFileName_))};
18  std::string instanceIdHash{std::to_string(std::hash<std::string>{}(instanceId_))};
19  std::string userHash{std::to_string(std::hash<std::string>{}(userName))};
20 
21  return "ChimeraTK_SharedDummy_" + instanceIdHash + "_" + mapFileHash + "_" + userHash;
22 }
23 
24 bool shm_exists(std::string shmName) {
25  bool result;
26 
27  try {
28  boost::interprocess::managed_shared_memory shm{boost::interprocess::open_only, shmName.c_str()};
29  result = shm.check_sanity();
30  }
31  catch(const std::exception& ex) {
32  result = false;
33  }
34  return result;
35 }
36 
37 // Use a file lock on dmap-file to ensure we are not running
38 // concurrent tests in parallel using the same shared dummies.
39 //
40 // Note: flock() creates an advisory lock only, plain file access is not
41 // prevented. The lock is automatically released when the process terminates!
42 struct TestLocker {
43  TestLocker(const char* dmapFile) {
44  // open dmap file for locking
45  fd = open(dmapFile, O_RDONLY);
46  if(fd == -1) {
47  std::cout << "Cannot open file '" << dmapFile << "' for locking." << std::endl;
48  exit(1);
49  }
50 
51  // obtain lock
52  int res = flock(fd, LOCK_EX);
53  if(res == -1) {
54  std::cout << "Cannot acquire lock on file '" << dmapFile << "'." << std::endl;
55  exit(1);
56  }
57  }
58 
59  int fd;
60 };
TestLocker::fd
int fd
Definition: sharedDummyHelpers.h:59
TestLocker::TestLocker
TestLocker(const char *dmapFile)
Definition: sharedDummyHelpers.h:43
MirrorRequestType::stop
@ stop
MirrorRequestType::from
@ from
TestLocker
Definition: testPcieBackend.cpp:51
MirrorRequestType::to
@ to
createExpectedShmName
std::string createExpectedShmName(std::string instanceId_, std::string mapFileName_, std::string userName)
Definition: sharedDummyHelpers.h:16
MirrorRequestType
MirrorRequestType
Definition: sharedDummyHelpers.h:13
shm_exists
bool shm_exists(std::string shmName)
Definition: sharedDummyHelpers.h:24
ChimeraTK::to_string
std::string to_string(Boolean &value)
Definition: SupportedUserTypes.h:59