C ++ Boost为两个不同的进程创建共享内存

时间:2013-06-14 18:31:56

标签: c++ windows boost shared-memory

所以,我正在尝试在C ++程序中创建一个共享内存段,所以我可以在其中编写一个简单的字符,并从另一个C ++程序中读取该字符。

我已经下载了Boost库,因为我阅读它简化了这个过程。 基本上我有两个问题:首先,如何在创建之后写入它?那么我应该在第二个程序中写什么来识别段并读取其中的信息?

这是我到目前为止所得到的。这不是很多,但我还是新手(第一个项目):

#include "stdafx.h"
#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>

int main(int argc, char *argv[])
{
   using namespace boost::interprocess;

   windows_shared_memory shared (create_only, "shm", read_write, 65536); 
   //created shared memory using the windows native library
   mapped_region region (shared, read_write, 0 , 0 , (void*)0x3F000000); 
   //mapping it to a region using HEX

   //Here I should write to the segment

   return 0;
}

提前致谢。我将非常乐意提供任何信息,以便获得适当的帮助。

1 个答案:

答案 0 :(得分:3)

以下是基于Boost documentation on Shared Memory

的略微修改的示例

注意:使用windows_shared_memory时请记住,共享内存块在使用它的最后一个进程存在时会自动销毁。在下面的示例中,这意味着,如果服务器在客户端进行更改以打开共享内存块之前存在,则客户端将抛出异常。

服务器端:

#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <cstdlib>
#include <string>

int main(int argc, char *argv[])
{
   using namespace boost::interprocess;

   //Create a native windows shared memory object.
   windows_shared_memory shm (create_only, "shm", read_write, 65536);

   //Map the whole shared memory in this process
   mapped_region region(shm, read_write);

   //Write a character to region
   char myChar = 'A';
   std::memset(region.get_address(), myChar , sizeof(myChar));

   ... it's important that the server sticks around, otherwise the shared memory 
       block is destroyed and the client will throw exception when trying to open

   return 0;
}

客户端:

#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <cstdlib>
#include <string>

int main(int argc, char *argv[])
{
   using namespace boost::interprocess;

   //Open already created shared memory object.
   windows_shared_memory shm (open_only, "shm", read_only);

   //Map the whole shared memory in this process
   mapped_region region(shm, read_only);

   //read character from region
   char *myChar= static_cast<char*>(region.get_address());


   return 0;
}

而不是memset共享内存中的原始字节,使用Boost.Interprocess可能会更好。它旨在简化通用进程间通信和同步机制的使用,并提供各种各样的 - 包括共享内存。例如,你可以create a vector in shared memory