我想了解以下代码的行为。
IDAInterface 是一个具有成员“myValue”的库。
C++:
#include <boost/interprocess/managed_shared_memory.hpp>
#include <cstdlib>
#include <idainterface.h>
IDAInterface ifIDA;
int main(int argc, char *argv[])
{
using namespace boost::interprocess;
typedef std::pair<IDAInterface, int> MyType; // [1]
if(argc == 1){ //Parent process
struct shm_remove{
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
} remover;
ifIDA.myValue = 15;
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
MyType *instance = segment.construct<MyType> ("MyType instance") (ifIDA, 0);
std::string s(argv[0]); s += " child ";
if(0 != std::system(s.c_str())) return 1;
std::cout<<"\nPROZESS 1 "<< ifIDA.myValue;
std::cout.flush();
//std::cout<<"\nPROZESS 1 "<< instance->first.myValue;
//std::cout.flush();
//segment.destroy<MyType>("MyType instance");
if(segment.find<MyType>("MyType instance").first) return 1;
}
else{
managed_shared_memory segment(open_only, "MySharedMemory");
std::pair<MyType*, managed_shared_memory::size_type> res;
res = segment.find<MyType> ("MyType instance");
if(res.second != 1) return 1;
IDAInterface nIFIDA;
nIFIDA = res.first->first;
std::cout<<"\nPROZESS 2 "<< nIFIDA.myValue;
std::cout.flush();
nIFIDA.EineZahl = 10;
std::cout<<"\nPROZESS 2 "<< nIFIDA.myValue;
std::cout.flush();
segment.destroy<MyType>("MyType instance");
}
return 0;
}
输出:
过程 2 15
过程 2 10
项目 1 15
项目 1 15
据我了解应该是进程1中的值,在运行进程2之后,也是10。为什么进程1中“myValue”的值总是15?以及如何在流程1中通过流程2获取“myValue”的修改值?