doc_windows_shared_memory.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/interprocess for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. #include <boost/interprocess/detail/config_begin.hpp>
  11. #include <boost/interprocess/detail/workaround.hpp>
  12. #if defined(BOOST_INTERPROCESS_WINDOWS) || defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
  13. //[doc_windows_shared_memory
  14. #include <boost/interprocess/windows_shared_memory.hpp>
  15. #include <boost/interprocess/mapped_region.hpp>
  16. #include <cstring>
  17. #include <cstdlib>
  18. #include <string>
  19. //<-
  20. #include "../test/get_process_id_name.hpp"
  21. //->
  22. int main(int argc, char *argv[])
  23. {
  24. using namespace boost::interprocess;
  25. if(argc == 1){ //Parent process
  26. //Create a native windows shared memory object.
  27. //<-
  28. #if 1
  29. windows_shared_memory shm (create_only, test::get_process_id_name(), read_write, 1000);
  30. #else
  31. //->
  32. windows_shared_memory shm (create_only, "MySharedMemory", read_write, 1000);
  33. //<-
  34. #endif
  35. //->
  36. //Map the whole shared memory in this process
  37. mapped_region region(shm, read_write);
  38. //Write all the memory to 1
  39. std::memset(region.get_address(), 1, region.get_size());
  40. //Launch child process
  41. std::string s(argv[0]); s += " child ";
  42. //<-
  43. s += test::get_process_id_name();
  44. //->
  45. if(0 != std::system(s.c_str()))
  46. return 1;
  47. //windows_shared_memory is destroyed when the last attached process dies...
  48. }
  49. else{
  50. //Open already created shared memory object.
  51. //<-
  52. #if 1
  53. windows_shared_memory shm (open_only, argv[2], read_only);
  54. #else
  55. //->
  56. windows_shared_memory shm (open_only, "MySharedMemory", read_only);
  57. //<-
  58. #endif
  59. //->
  60. //Map the whole shared memory in this process
  61. mapped_region region(shm, read_only);
  62. //Check that memory was initialized to 1
  63. char *mem = static_cast<char*>(region.get_address());
  64. for(std::size_t i = 0; i < region.get_size(); ++i)
  65. if(*mem++ != 1)
  66. return 1; //Error checking memory
  67. return 0;
  68. }
  69. return 0;
  70. }
  71. //]
  72. #else //BOOST_INTERPROCESS_WINDOWS
  73. int main()
  74. {
  75. return 0;
  76. }
  77. #endif //BOOST_INTERPROCESS_WINDOWS
  78. #include <boost/interprocess/detail/config_end.hpp>