如何在 POSIX 共享内存中使用结构?

How to use struct in POSIX shared memory?

我希望我的 POSIX 共享内存段符合特定结构。我认为这段代码以结构的形式创建了共享内存段。

(File creating the shared memory segment)

typedef struct {
  int cnt;
  char buf[segsize];
} shmseg_t;

int shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, sizeof(shmseg_t);
void* addr = mmap(NULL, sizeof(shmseg_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);

如何将文件中的数据写入共享内存中结构的不同字段?

(File writing to the shared memory segment)

int shm_fd = shm_open(shm_name, O_WRONLY, 0);
ftruncate(shm_fd, segsize);
void* addr = mmap(NULL, segsize, PROT_WRITE, MAP_SHARED, shm_fd, 0);
// How do I get shmp, which should be a shmseg_t struct?
shmp->cnt = read(fd, shmp->buf, segsize);

以及如何取出写入共享内存中结构的数据?

(File reading from the shared memory segment)

int shm_fd = shm_open(shm_name, O_RDONLY, 0);
ftruncate(shm_fd, segsize);
void* addr = mmap(NULL, segsize, PROT_READ, MAP_SHARED, shm_fd, 0);
// How to get out shmp->cnt and shmp->buf?

不清楚您是要共享整个结构还是只共享 buf

选项 1: 使 buf 成为一个指针,并分享它指向的内容。

typedef struct {
  int cnt;
  char *buf;
} shmseg_t;

ftruncate(shm_fd, segsize);
void* addr = mmap(NULL, segsize,
                  PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
assert(addr != MAP_FAILED);

shm_seg_t shmp = {
    .cnt = ???,  // Whatever value of cnt you want.
    .buf = addr,
};

选项 2:共享整个结构。

typedef struct {
  int cnt;
  char buf[segsize];
} shmseg_t;

ftruncate(shm_fd, sizeof(shmseg_t));
void* addr = mmap(NULL, sizeof(shmseg_t),
                  PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
assert(addr != MAP_FAILED);

shm_seg_t *shmp = addr;

这样分享的话,读和写其实没什么区别(但是需要用到内存屏障或者同步)