我正在创建一个服务器和一个客户机,它们同时访问共享内存并更改共享内存中的数据。
我使用shm_open打开共享内存,使用ftruncate更改共享内存的大小,使用mmap映射结构类型的共享内存对象。
我希望创建一个函数,该函数通过文件描述符访问共享内存,并返回指向结构的指针。
例如:
XStruct * accessMem(int fd){ /*what to do here? */};我不知道如何实现这一点,也不知道如何使用哪些函数来访问共享内存。任何帮助都会很好。
这是作业,所以解释会很有帮助。
谢谢!
发布于 2017-03-01 10:17:11
您必须使用(或实现内存分配器来处理从mmap收到的块)。
一个简单的实现可以是使用凸起分配器。
存储从mmap收到的指针的值。每次需要为结构分配内存时,都要将指针增加多少( struct )并返回原始指针。
void *allocator_top; // Define a global pointer to top of the "heap" area.
.
.
.
allocator_top = mmap(...); // Do this wherever you perform the mmap
.
.
Xstruct * accessMem(){
void *temp = allocator_top;
// Need to check here if you have exceeded the amount of space mapped. If yes, you need to expand and add more pages.
allocator_top += sizeof(Xstruct);
return temp;
}编辑:如果您有多个共享区域,并且希望单独分配,则可以将一个空**allocator_top作为参数传递给accessMem(),并传递要从其中分配的区域的顶部。
https://stackoverflow.com/questions/42528570
复制相似问题