我使用boost文档中的示例但是,它没有工作=( 这是服务器应用程序,在这种情况下可以
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <cstring>
#include <cstdlib>
#include <string>
#include <iostream>
using namespace boost::interprocess;
typedef allocator<int,managed_shared_memory::segment_manager> ShmemAllocator;
typedef vector<int, ShmemAllocator> MyVector;
int main(int argc, char *argv[])
{
struct shm_remove
{
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
} remover;
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
const ShmemAllocator alloc_inst (segment.get_segment_manager());
MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst);
for (int i=0;i<100;i++) myvector->push_back(i);
MyVector *myanothervector = segment.find<MyVector>("MyVector").first;
std::cout<<"found\n";
for(int i=0;i<100;i++) std::cout<<(*myanothervector)[i];
char c;//pause
std::cin>>c;
return 0;
}
但是在客户端应用程序中我无法找到向量,当我尝试在managed_shared_memory中找到向量时,我的程序已冻结(服务器应用已经启动并且在我启动客户端应用时仍在工作)
//client app
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <string>
#include <cstdlib> //std::system
#include <iostream>
using namespace boost::interprocess;
typedef allocator<int,managed_shared_memory::segment_manager> ShmemAllocator;
typedef vector<int, ShmemAllocator> MyVector;
int main(int argc, char *argv[])
{
managed_shared_memory segment(open_only, "MySharedMemory");
MyVector *somevector = segment.find<MyVector>("MyVector").first;// my program freezed here
std::cout<<"found\n";
for(int i=0;i<100;i++) std::cout<<(*somevector)[i];
segment.destroy<MyVector>("MyVector");
}