开发者

C Shared memory pointer mapping

I have a data structure as follows:

struct s1{
unsigned char* ptr;//points to an element in the shared memory
};

struct s1* s1Arr;

And I allocated a shared memory block and the pointer to it is:

unsigned char* shm_ptr.

I have an array of s1, with the same number of elements as there are elements in the shm_ptr array I allocated.

//point all the ptr elements of the struct to the shared memory elements(parallel array)
for(i = 0; i < count; i++)
{
shm_ptr[i] = 99;
s1Arr[i].ptr = &shm_ptr[i];
printf("val=%d\n". *s1Arr[i].ptr);
}

When I go to print *s1Arr[i].ptr, it only prints i, where i is 0, 1...while it should be printing 99. Any thoughts as to what I am doing wrong?

I know the shared memory is working as I have tried to access it from another process.

void* allocArray_开发者_如何学Goshared(int elementCount, int elementByteSize, int* shmid, key_t key)
{
    printf("allocshared errno=%d\n", errno);
    //size of entire array(cols*rows* byte size + row pointers)
    int array_size = elementByteSize * elementCount;


    //Allocate enough space for all elements + row pointers
    *shmid = shmget(key, array_size, 0666 | IPC_CREAT);

    char * arr = (char*)shmat(*shmid, NULL, 0);
    if(!arr) return NULL;

    printf("allocshared end errno=%d\n", errno);

    //Return the pointer to the first row pointer
    return (void*)arr;
}

EDIT: Found the issue..was allocating multiple shared memory segments with the same key and thus reads/writes were overlapping...ugh...


I get 99 displayed 5 times with this code. I think the only change is that I removed the keyword struct from the beginning of your struct array declaration (it was struct s1 * s1Arr).

EDIT: I put the struct keyword back in and got the same result, so I don't really know why my results are different than yours.

struct s1
{
    unsigned char * ptr;  //points to an element in the shared memory
};

s1 * s1Arr = new s1[5];
unsigned char * shm_ptr = new unsigned char[5];

for(int i = 0; i < 5; i++)
{
   shm_ptr[i] = 99;
   s1Arr[i].ptr = &shm_ptr[i];
   cout << ((int)*s1Arr[i].ptr) << "\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜