Cheetah Software  1.0
test_sharedMemory.cpp
Go to the documentation of this file.
1 
8 
9 #include "gmock/gmock.h"
10 #include "gtest/gtest.h"
11 
13 struct TestType {
16 };
17 } // namespace SharedMemoryTestNamespace
18 
19 using namespace SharedMemoryTestNamespace;
20 
21 // test shared memory
22 TEST(SharedMemory, MemoryAndSemaphore) {
23  SharedMemoryObject<TestType> sharedObject, oldStaleSharedMemory;
24  std::string memoryName = "/shared-memory-test";
25 
26  // first open and close shared memory to reset everything
27  // allow overwriting because the last run of the test could have left memory
28  // open
29  sharedObject.createNew(memoryName, true);
30  EXPECT_TRUE(sharedObject.get());
31  sharedObject.closeNew();
32 
33  // now we should be able to open shared memory without overwriting
34  EXPECT_FALSE(oldStaleSharedMemory.createNew(memoryName, false));
35  oldStaleSharedMemory.get()->value =
36  12; // this shouldn't segfault if the memory is mapped succesfully
37 
38  // now we should have to overwrite already existing shared memory
39  EXPECT_TRUE(sharedObject.createNew(memoryName, true));
40  sharedObject.closeNew(); // and close it
41 
42  // now we can open without overwriting
43  EXPECT_FALSE(sharedObject.createNew(memoryName, false));
44 
45  const u32 valueFromParent = 2;
46  const u32 valueFromChildSuccess = 3;
47  const u32 valueFromChildFailure = 4;
48 
49  // value should be zeroed
50  EXPECT_TRUE(0 == sharedObject.get()->value);
51  // set up tosend value from parent to child process
52  sharedObject.get()->value = valueFromParent;
53  sharedObject.get()->semaphore.init(0);
54 
55  // create child process
56  pid_t pid = fork();
57  if (!pid) {
58  // child runs this: open shared memory
60  childView.attach(memoryName);
61 
62  // check to see we got the correct value:
63  if (childView().value == valueFromParent) {
64  childView().value = valueFromChildSuccess;
65  } else {
66  // otherwise signal an error
67  childView().value = valueFromChildFailure;
68  }
69 
70  // inform the parent that it can now read the child value from shared memory
71  childView().semaphore.increment();
72 
73  // close our view and exit child process
74  childView.detach();
75  exit(0);
76  }
77 
78  sharedObject.get()->semaphore.decrement(); // wait until child writes
79  EXPECT_TRUE(valueFromChildSuccess == sharedObject.get()->value);
80  sharedObject.closeNew();
81 }
Shared memory utilities for connecting the simulator program to the robot program.
void attach(const std::string &name)
Definition: SharedMemory.h:191
void init(unsigned int value)
Definition: SharedMemory.h:39
uint32_t u32
Definition: cTypes.h:18
bool createNew(const std::string &name, bool allowOverwrite=false)
Definition: SharedMemory.h:125
TEST(SharedMemory, MemoryAndSemaphore)