1

I'm using Boost Shared Memory to share a vector across processes.

In the client, how can I, once I try and open the shared memory and read a vector off it, realize if the memory is not valid, or is not what I'm looking for.

Will the Open_Only fail if the memory segment does not exist, and if so, how do I catch this failure?

Also, the shared memory segment is supposed to be removed, if there are no references to it. However, in my case, even when both the client and server are shut down, and nothing else is accessing the shared memory, the segment remains in Boost Interprocess folder in Program data, with some data. So the next time client starts up, it has no problem opening up the segment, and so thinks it is accessing correct data when in fact, there is no data to be shared.

Kindly advise. Thank you.

user1173240
  • 1,455
  • 2
  • 23
  • 50

1 Answers1

0

Speaking from experience with the underlying shm api--and not as a Boost expert...

To determine validity, one technique is to figure out if the current process is the one that is creating the shared memory (the first time). You can do this by getting the size after creating (fstat) and seeing if the size is zero. If it is zero, the process is creating it. Once you know that you can initialize it. Also, when you call truncate() to set the size here, that size is set for all other processes.

To ensure removal, you can call shm_unlink() to remove the shared memory file from the system. I believe in Boost there is a remove() api that will do that.

Yasser Asmi
  • 1,150
  • 2
  • 12
  • 27
  • I'm not sure about the size. In some cases, I was getting the size as 0, but the capacity as the correct number. So not sure of using that as a check. In Boost, there is a segment destroyer, but it only works in case all links to it are removed. So, if the server isn't pushing anything and has gone off, what tells the client to stop referring to the shared memory and signal an error? – user1173240 Mar 13 '14 at 10:32
  • At the shared memory level, there is no mechanism that tells a client that server has gone. Actually, there is no concept of the server vs client. It is basically just a piece of memory shared between processes. Other mechanisms are built on top of it. Does your shm file show up /dev/shm folder while it is in use? – Yasser Asmi Mar 13 '14 at 20:36
  • 1
    Another idea is to write some kind of always incrementing number (timestamp?) every once in a while to the shared memory. And compare that with the values clients have. – Yasser Asmi Mar 13 '14 at 20:38
  • Thank you for the suggestion. I'd hoped there'd be an easier method, but this will have to do, I suppose, unless I uncover something else. – user1173240 Mar 20 '14 at 10:15