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

时间:2016-10-31 20:38:03

标签: c dynamic process shared-memory mmap

我有两个访问同一共享内存的进程。但是我想在共享内存中存储一​​个动态分配的数组。我知道这可以使用灵活的阵列成员来实现,但我不允许使用它们。

我能够从服务器分配和访问动态数组,但每当我的客户端尝试访问它时,我都会遇到段错误。我可以很好地访问其他结构成员。这是我的代码的逻辑。我在共享内存段的末尾分配了一些额外的空间,并将数组设置为指向段的末尾。

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

解决方案是在结构外定义另一个列表

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]);