Question

I have 2 applications that are using a shared memory segment to pass data from a writing process to a reading process. At the top of the shared memory segment, I want to declare a single header struct to contain general segment data such as buffer count values, read/write offsets, pthread mutex/condition variables, etc. The header struct does NOT contain any pointers. Then the rest of the segment is used for the actual data being passed between the 2 processes.

Since the shared memory segment is attached to the process, I am assured that the segment is indeed valid/accessible to the process. It is easy to simply cast the base segment pointer to a pointer of the header struct type and that works very well for regular data types (like ints, etc) but does not work for the non-integral data types in the struct like pthread mutex/condition variables since they have not actually been declared and allocated.

So, how do I declare and allocate my header struct to start at the specific address of my already allocated shared memory segment?

The following does not appear to work:

SmHeader header = *((SmHeader *)m_pBaseAddress);

m_pHeader = &header;

where SmHeader is a typedef of my header struct and m_pBaseAddress is the base address of the attached shared memory segment.

thanks, -Andres

Was it helpful?

Solution

I think it doesn't work because of the way you're creating it:

// this creates a copy of the SmHeader struct, on the stack
SmHeader header = *((SmHeader *)m_pBaseAddress);

// this sets m_pHeader to address of the local variable, not
// m_pBaseAddress
m_pHeader = &header;

Try this instead:

m_pHeader = (SmHeader *) m_pBaseAddress;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top