Open iamysx opened 1 month ago
Without a fully compilable example and the details of your compilation platform it's difficult to know which is the problem.
But I suspect that as soon as one child process exits, the destructor for "remover" runs (since it shares code with the parent process the destructor of "remover" deletes the shared memory, so later running children can't open it.
include <boost/interprocess/managed_shared_memory.hpp>
include <boost/interprocess/containers/map.hpp>
include <boost/interprocess/allocators/allocator.hpp>
include <boost/interprocess/sync/interprocess_mutex.hpp>
include <boost/interprocess/sync/scoped_lock.hpp>
include
include
include
include <sys/wait.h>
include
typedef int KeyType; typedef float MappedType; typedef std::pair<const int, float> ValueType; using namespace boost::interprocess;
const char *shared_memory_name = "MySharedMemory";
// Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove(shared_memory_name); } ~shm_remove() { shared_memory_object::remove(shared_memory_name); } } remover;
struct SharedData { interprocess_mutex mutex; typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator; typedef map<KeyType, MappedType, std::less, ShmemAllocator> MyMap;
ShmemAllocator alloc_inst;
MyMap mymap;
};
void child_process(int id) { try { // Open the shared memory managed_shared_memory segment(open_only, shared_memory_name); SharedData *data = segment.find("MySharedData").first;
}
int main() { const int num_children = 1;
}
result: Child 1 inserted value 1 Child 2 inserted value 2 Child process exception: No such file or directory Parent process reading map values: Key: 0, Value: 0 Key: 1, Value: 1 Key: 2, Value: 2 done