Ticket #1390: test.cpp

File test.cpp, 1.7 KB (added by samalone@…, 14 years ago)

Code to reproduce this bug

Line 
1#include <unistd.h>
2#include <iostream>
3#include <sys/wait.h>
4#include <boost/interprocess/managed_shared_memory.hpp>
5#include <boost/interprocess/sync/scoped_lock.hpp>
6#include <boost/interprocess/sync/named_mutex.hpp>
7
8using namespace boost::interprocess;
9
10int main() {
11
12 // Remove any shared memory from a previous test run.
13 shared_memory_object::remove("sharedMemTest");
14 named_mutex::remove("sharedMemTestMutex");
15
16 // Create a second copy of this process so that we have two processes
17 // modifying the shared memory. We don't care which is the parent and
18 // which is the child, since they will be doing the same operations.
19 int child_pid = fork();
20
21 try {
22 managed_shared_memory shared(open_or_create, "sharedMemTest", 2048);
23 named_mutex mutex(open_or_create, "sharedMemTestMutex");
24
25 for (int i = 0; i < 10000; ++i) {
26 {
27#if EXTRA_MUTEX
28 scoped_lock<named_mutex> lock(mutex);
29#endif
30 shared.find_or_construct<long>("key")();
31 }
32 {
33#if EXTRA_MUTEX
34 scoped_lock<named_mutex> lock(mutex);
35#endif
36 shared.destroy<long>("key");
37 }
38 }
39 }
40 catch (const std::exception & e) {
41 std::cerr << "Unhandled exception: " << e.what() << std::endl;
42 }
43
44 // Since the shell will not print the exit status of the child process,
45 // print it ourselves.
46 if (child_pid) {
47 int child_status;
48 waitpid(child_pid, &child_status, 0);
49 if (WIFSIGNALED(child_status)) {
50 std::cerr << "child exited with signal " << WTERMSIG(child_status) << std::endl;
51 }
52 else {
53 std::cout << "Test passed." << std::endl;
54 }
55 }
56
57 return 0;
58}