Interprocess.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #pragma once
  2. #include <boost/interprocess/sync/scoped_lock.hpp>
  3. #include <boost/interprocess/sync/interprocess_mutex.hpp>
  4. #include <boost/interprocess/sync/interprocess_condition.hpp>
  5. #include <boost/interprocess/mapped_region.hpp>
  6. #include <boost/interprocess/shared_memory_object.hpp>
  7. /*
  8. * Interprocess.h, part of VCMI engine
  9. *
  10. * Authors: listed in file AUTHORS in main folder
  11. *
  12. * License: GNU General Public License v2.0 or later
  13. * Full text of license available in license.txt file, in main folder
  14. *
  15. */
  16. struct ServerReady
  17. {
  18. bool ready;
  19. uint16_t port; //ui16?
  20. boost::interprocess::interprocess_mutex mutex;
  21. boost::interprocess::interprocess_condition cond;
  22. ServerReady()
  23. {
  24. ready = false;
  25. port = 0;
  26. }
  27. void waitTillReady()
  28. {
  29. boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> slock(mutex);
  30. while(!ready)
  31. {
  32. cond.wait(slock);
  33. }
  34. }
  35. void setToReadyAndNotify(const uint16_t Port)
  36. {
  37. {
  38. boost::unique_lock<boost::interprocess::interprocess_mutex> lock(mutex);
  39. ready = true;
  40. port = Port;
  41. }
  42. cond.notify_all();
  43. }
  44. };
  45. struct SharedMemory
  46. {
  47. const char * name;
  48. boost::interprocess::shared_memory_object smo;
  49. boost::interprocess::mapped_region * mr;
  50. ServerReady * sr;
  51. SharedMemory(std::string Name, bool initialize = false)
  52. : name(Name.c_str())
  53. {
  54. if(initialize)
  55. {
  56. //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  57. boost::interprocess::shared_memory_object::remove(name);
  58. }
  59. smo = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create, name, boost::interprocess::read_write);
  60. smo.truncate(sizeof(ServerReady));
  61. mr = new boost::interprocess::mapped_region(smo,boost::interprocess::read_write);
  62. if(initialize)
  63. sr = new(mr->get_address())ServerReady();
  64. else
  65. sr = reinterpret_cast<ServerReady*>(mr->get_address());
  66. };
  67. ~SharedMemory()
  68. {
  69. delete mr;
  70. boost::interprocess::shared_memory_object::remove(name);
  71. }
  72. };