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