Home > Enterprise >  How to solve Boost Error: terminate called after throwing an instance of 'boost::interprocess::
How to solve Boost Error: terminate called after throwing an instance of 'boost::interprocess::

Time:09-08

I am trying to use Boost for creating a shared memory. This is my code:

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>

#define BUF_SIZE            1*1024*1024

int main()
{
    shared_memory_object tx_data_buffer(create_only ,"tx_data_memory", read_write);
    tx_data_buffer.truncate(BUF_SIZE);
    mapped_region tx_region(tx_data_buffer, read_write);

    //Get the address of the region
    cout << "\n\nTX Data Buffer Virtual Address = " << tx_region.get_address() << endl;

    //Get the size of the region
    cout << "\n\nTX Data Buffer Size = " << tx1_region.get_size() << endl;
}

I ran the above code succesfully a few times before (not sure whether it was one time or more than one times). But when I am trying to run the same code again, it is giving me the following error:

terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
  what():  File exists

I am running the code on Eclipse in Linux. Any idea as to what is causing this?

CodePudding user response:

You're specifically asking the shared_memory_object to open in create_only mode. Of course, when it exists, it cannot be created, so it fails. The error message is very clear: "File exists".

One way to resolve your problem is to use open_or_create instead:

namespace bip = boost::interprocess;

bip::shared_memory_object tx_data_buffer(bip::open_or_create ,"tx_data_memory", bip::read_write);

Or, alternatively, explicitly delete the shared memory object:

bip::shared_memory_object::remove("tx_data_buffer");
bip::shared_memory_object tx_data_buffer(bip::create_only, "tx_data_memory",
                                         bip::read_write);

Keep in mind that you have synchronize access to shared memory from different threads.

  • Related