将结构数组复制到共享内存中

时间:2016-02-19 14:29:50

标签: c ipc shared-memory

我有多个进程在相同的数据上运行。我想将数据保存在共享内存中。问题是我似乎无法保存(或检索)。

我的完整代码在这里: https://github.com/kasperekt/LLGame/blob/master/server_src/game_state.c#L74

但似乎问题出在这些功能中:

typedef struct game_state {
  int resources;
  int wins;
  army_t *army;
} game_state_t;

...

static game_state_t *players[2] = { NULL, NULL };
static game_state_t **mem_state = NULL;

...

void attach_state() {
  mem_state = get_memory_data(0);
  players[0] = mem_state[0];
  players[1] = mem_state[1];
}

void save_state() {
  if (mem_state == NULL) {
    mem_state = get_memory_data(0);
  }

  mem_state[0] = players[0];
  mem_state[1] = players[1];
  detach_memory_data(mem_state);
}

可用于此数据的示例函数:

void increment_resources(int player_id) {
  attach_state();
  const int workers_count = players[player_id]->army->workers;
  players[player_id]->resources += RESOURCES_STEP + (workers_count * 5);
  save_state();
}

我应该如何将其保存到内存中?它是如何工作的?我找不到答案。

也许这段代码也会有所帮助:

game_state_t **get_memory_data(char *shmaddr) {
  const int shmat_flag = 0;
  return shmat(memory_id, shmaddr, shmat_flag);
}

void detach_memory_data(game_state_t **data) {
  if (shmdt(data) == -1) {
    perror("Error detaching memory: ");
    exit(1);
  };
}

1 个答案:

答案 0 :(得分:1)

你有game_state_t变量。如果要存储多个状态,则只需要单维数组。这是样本。

game_state_t *memstate;
...
memstate = (game_state_t *) malloc( n * sizeof(game_state_t)); /* alloc memory for n states */

shmptr = shmat(...);

memcpy(shmptr, memstate, size);  /* size for example n * size of(game_state_t)); */

或者只使用共享内存。

memstate = shmat(...);

如注释中所示,结构的指针成员需要指向共享内存。

实施例

memstate.x = memstate + offset; /* use different offsets based on your usage */