我可以将结构映射到共享内存文件吗?

时间:2016-10-12 05:35:57

标签: c struct posix shared-memory

我正在尝试在主进程中打开共享内存段。我的术语在问题中可能不正确,但这正是我想要实现的目标:

我从7个传感器收集信息,并从中评估状态。我制作了一个结构senStruct。我想使用共享内存将7传感器和状态信息共享给其他进程。在代码中,我打开senfile,将senStruct映射到其中。现在我只想将某些东西存入状态并且它给我一个错误。

以下是代码:

#include <fcntl.h> /* Defines O_* constants */
#include <sys/stat.h> /* Defines mode constants */
#include <sys/mman.h>   
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

typedef struct senStruct {
    int sensor[7];
    int state;
}senStruct;

int main()
{
    int fd;
    size_t size = sizeof(senStruct);
    senStruct *p;
    fd = shm_open( "senfile" , O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR );
    ftruncate (fd, size);
    printf("Before mapping...p points to %p\n",p);
    p =(senStruct *) mmap (NULL , size, PROT_READ | PROT_WRITE,MAP_SHARED , fd, 0);
    printf("After mapping...p points to %p\n",p);
    p->state=1;
    return 0;
}

输出是:

Before mapping...p points to (nil)
After mapping...p points to 0xffffffffffffffff
Segmentation fault (core dumped)

p之后p的地址似乎对我有疑问。查看gdb表示p->state = 1处的分段错误。我的手术不正确还是我错过了什么?

0 个答案:

没有答案
相关问题