我在进程之间共享向量时遇到问题。我可以共享矢量,甚至可以从不同的过程中获得矢量的大小,但是当我在函数中使用时,程序会崩溃。
struct B
{
std::vector<int> vec;
};
int main(int cArgs, char* ppszArgs[])
{
if (cArgs == 1) { //Parent process
//Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove() { shared_memory_object::remove("MySharedMemory"); }
} remover;
//Create a shared memory object.
shared_memory_object shm(create_only, "MySharedMemory", read_write);
//Set size
shm.truncate(1000);
//Map the whole shared memory in this process
mapped_region region(shm, read_write);
//Write all the memory to 1
B* test = new B();
CopyMemory(region.get_address(), test, sizeof(B));
parentProcess(); -> this method just starts the child process
int index = 1;
while (true)
{
if(index < 2)
{
((B*)region.get_address())->vec.push_back(index);
}
++index;
}
}
else
{
//Open already created shared memory object.
shared_memory_object shm(open_only, "MySharedMemory", read_only);
//Map the whole shared memory in this process
mapped_region region(shm, read_only);
//Check that memory was initialized to 1
HANDLE mem = region.get_address();
while(true)
{
std::cout << ((B*)mem)->vec.at(0) << std::endl; -> if for example i put
lista.size(), then i will get the number of items in vector.
}
}
}
我的问题甚至可以从子进程访问矢量元素吗?
要共享数据,您需要使用共享内存机制(对于Linux和CreateFileMapping为PC共享内存,对于Windows为MapViewOfFile,...),但这不允许您共享诸如矢量之类的复杂对象。
想象P1
进程创建一个向量并存储一些元素。
Vector_P1 <element1, element2, element3, ...>
element1, element2, element3
已在P1
(P1的堆)的地址空间中创建,我们假设:
[将向量作为对象共享时,P2进程将使用不属于其地址空间的地址0xAB123456, 0xCD123456, 0xDE123456
,这将导致memory access violation
您只能共享的是PODS类型。一旦传递了new
保留的复杂对象,它将无法正常工作