I am trying to share an unordered map(hash map) but it is ending up with the Floating point exception at the line where it tries to insert the data in the map.
Could someone please help in understanding where I am going wrong?
#include <iostream>
#include <string>
#include <unordered_map>
#include <sys/ipc.h>
#include <sys/shm.h>
int main ()
{
std::unordered_map<std::string,double> *tmp;
key_t key = 5678;
int shmid = shmget(key, 1000, IPC_CREAT | IPC_EXCL | 644);
if(shmid == -1){
std::cerr << "Failed to create the shared segment." << std::endl;
exit(-1);
}
void *addr = shmat(shmid, NULL, 0);
if(addr == (void*)-1){
std::cerr << "Failed to attach the segment to the process." << std::endl;
exit(-1);
}
tmp = static_cast< std::unordered_map<std::string,double>* >(addr);
tmp->insert (std::pair<std::string,double>("abc",1.2));
shmdt(addr);
return 0;
}
Thanks.
In general, you can’t share complex structures between processes. In particular, pointers to objects in the virtual address space of one process won’t be valid in another, and most container implementations will involve pointers.
You could look at the Boost.Interprocess library which contains various containers and allocators suitable for sharing; in particular, their version of
unordered_mapcan be placed in shared memory, as long as you use their shared memory allocator, so you might simply be able to use that as a replacement forstd::unordered_map(although you’d still need a replacement forstd::stringas the key).