我有一个包含这样的数组元素的结构
#define SIZE 20
typedef struct
{
int currentindex;
int array[SIZE];
} tempstruct;
int main()
{
int fd;
tempstruct *ptr = NULL;
fd = shm_open("/TESTPROG", O_RDWR | O_CREAT, 0666);
ptr = mmap(0,sizeof(tempstruct),PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
/*
So in case SIZE is not compile time constant but another int then I do this
ptr = mmap(0,sizeof(tempstruct),PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
ptr.array = (int*)malloc(sizeof(int)*SIZE);
*/
return 0;
}
如您所见,我使用 mmap
在共享内存区域分配此 tempstruct
的实例,但现在由于一些更改,我想动态分配 的数组元素code>tempstruct
结构作为 SIZE
不会是编译时常量。那么上面的程序仍然有效吗?比如我可以在堆上分配数组,然后 mmap
将其分配到共享内存,这样另一个进程中的数组会指向同一个堆区域吗?我想不会,所以请提出一些更好的方法?
谢谢
最佳答案
下面是解决这个问题的一种方法:
typedef struct
{
int currentindex;
int array[0];
}
tempstruct;
int main()
{
...
int totalSize = sizeof(tempstruct) + sizeof(int) * numOfElements;
ptr = mmap(0, totalSize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
...
}
请注意,您将无法正确使用 tempstruct
实例数组。
关于c - 对于 mmaped 结构,静态数组更改为动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23132031/