简体   繁体   English

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

[英]Copying array of structs into shared memory

I have multiple processes operating on the same data. 我有多个处理相同数据的进程。 I want to keep the data inside shared memory. 我想将数据保留在共享内存中。 Problem is it seems I can't save into it (or retrieve). 问题是似乎我无法将其保存(或检索)。

My whole code for it is here: https://github.com/kasperekt/LLGame/blob/master/server_src/game_state.c#L74 我的整个代码在这里: https : //github.com/kasperekt/LLGame/blob/master/server_src/game_state.c#L74

but it seems that the problem is inside these functions: 但似乎问题出在以下功能内:

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);
}

And example function which works on this data: 和处理此数据的示例函数:

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();
}

How I should save it into memory? 我应该如何将其保存到内存中? How does it work? 它是如何工作的? I can't find answer for this. 我找不到答案。

Maybe this code will also help: 也许这段代码也会有所帮助:

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);
  };
}

You have game_state_t variable. 您有game_state_t变量。 If you are storing multiple states, you only need single dimension array. 如果要存储多个状态,则只需要一个维数组。 Here is the sample. 这是示例。

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)); */

OR Simply use only the shared memory. 或仅使用共享内存。

memstate = shmat(...);

As indicated in the comments, the pointer members of the structure need to point to the shared memory. 如注释中所示,结构的指针成员需要指向共享内存。

Example; 例;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM