1

我有这个结构:

typedef struct ip_row {
  sem_t row_lock;
  char row_name[NAME_SIZE];
  char row_address4[NAME_SIZE]; // IPv4 address name
  char row_address6[NAME_SIZE]; // IPv6 address name
} ip_row_t;

我想在共享内存文件中多次使用该结构。我已经验证了它仅用于一次用途。

int shmfd; //Shared memory file descriptor
struct ip_row *data;

/*...creating shared memory and map...*/
shmfd = shm_open(shared_memory, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP );
ftruncate(shmfd,FILESIZE);
data = (ip_row_t*)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0);

/*...getting to user inputs, this stuff is in a loop...*/
strcpy(data->row_name,ipstr1);       
strcpy(data->row_address6,ipstr2);  
strcpy(data->row_address4,ipstr3);

当我再次运行循环时,写入从共享内存文件的开头开始,覆盖之前的内容。如何移动偏移量以便支持更多条目进入共享内存?我试过这两个:

lseek(shmfd,sizeof(struct ip_row_t),SEEK_CUR); //segfault when we write agian
data = (ip_row_t*)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,sizeof(struct ip_row_t)); //also segfaults when we try to read

任何建议将不胜感激。`

4

1 回答 1

1

You should use pointer arithmetic on struct ip_row *data; to reach "further" in your mmaped shared memory since mmap returns nothing but a pointer to a memory region of FILESIZE, which happens to be mirrored into shared memory.
For example use data[0] to access first copy, data[1] to access second etc.

lseek on shared memory object is unspecified and your second mmap causes segfault because you are trying to mmap FILESIZE bytes to a FILESIZE memory region that has been allocated to you but at an sizeof(struct ip_row_t) offset, thus effectively going outside the memory you are allowed to access, besides, offset has to be multiple of getpagesize(), which in this case it probably is not.

于 2014-12-02T21:47:25.293 回答