[英]C struct member pointer in 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
任何帮助,将不胜感激!
解决方案是在结构外部定义其他列表
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.