简体   繁体   English

共享内存中的C struct成员指针(mmap)

[英]C struct member pointer in shared memory (mmap)

I have two processes that access the same shared memory. 我有两个访问同一共享内存的进程。 However I want to store a dynamically allocated array in shared memory. 但是我想在共享内存中存储动态分配的数组。 I know this can be achieved using flexible array members but I am not allowed to use them. 我知道可以通过使用灵活的数组成员来实现,但不允许使用它们。

I am able to allocate and access the dynamic array from the server but whenever my client attempts to access it I get a segfault. 我能够从服务器分配和访问动态数组,但是只要我的客户端尝试访问它,我都会遇到段错误。 I can access other structure members just fine nontheless. 尽管如此,我仍然可以访问其他结构成员。 Here is the logic of my code. 这是我的代码的逻辑。 I allocated some extra space at the end of the shared memory segment and set the array to point to the end of the segment. 我在共享内存段的末尾分配了一些额外的空间,并将数组设置为指向该段末尾。

struct A{
    int a;
    struct B *other;
}
struct B{
    int b;
}
...
//Server
fd=shm_open("shared", O_CREAT | O_RDWR, 0666);
ftruncate(fd, sizeof(struct A)+200*sizeof(struct B));
struct A *ptr=mmap(NULL, sizeof(struct A)+200*sizeof(struct B), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
ptr->other=(struct B *)(ptr+1);       
int i=0;
for(i=0;i<200;i++){
    struct B b;
    ptr->other[i]=b;
}
...
//Client
int fd=shm_open("shared", O_RDWR, 0666);
struct A *ptr=mmap(NULL, sizeof(struct A)+200*sizeof(struct B), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
printf("%i", ptr->other[0]);// SEGFAULT

Any help would be appreciated! 任何帮助,将不胜感激!

The solution was to define the other list outside the structure 解决方案是在结构外部定义其他列表

struct A{
    int a;
}
struct B{
    int b;
}
...
//Server
fd=shm_open("shared", O_CREAT | O_RDWR, 0666);
ftruncate(fd, sizeof(struct A)+200*sizeof(struct B));
struct A *ptr=mmap(NULL, sizeof(struct A)+200*sizeof(struct B), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
struct B *other=(struct B *)(ptr+1);      
int i=0;
for(i=0;i<200;i++){
    struct B b;
    other[i]=b;
}
...
//Client
int fd=shm_open("shared", O_RDWR, 0666);
struct A *ptr=mmap(NULL, sizeof(struct A)+200*sizeof(struct B), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
struct B *other=(struct B *)(ptr+1); 
printf("%i", other[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM