[英]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. 我有一个s1数组,其元素数与我分配的shm_ptr数组中的元素数相同。
//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? 当我打印* s1Arr [i] .ptr时,它仅打印i,其中i为0、1 ...而应该打印99。关于我在做什么错的任何想法?
I know the shared memory is working as I have tried to access it from another process. 我知道共享内存正在工作,因为我尝试从另一个进程访问它。
void* allocArray_shared(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. 使用此代码,我得到99次显示5次。 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
). 我认为唯一的变化是我从结构数组声明的开头删除了关键字struct
(它是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
关键字,并得到相同的结果,所以我真的不知道为什么我的结果与您的不同。
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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.