3

所以,我正在尝试在 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;
}

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

4

1 回答 1

4

以下是基于共享内存的 Boost 文档的稍作修改的示例

注意:使用时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。它旨在简化常见进程间通信和同步机制的使用,并提供范围广泛的它们——包括共享内存。例如,您可以在共享内存中创建一个向量

于 2013-06-14T19:36:40.740 回答