我有多个进程在同一数据上运行。我想把数据保存在共享内存中。问题是我似乎无法保存(或检索)。
我的密码在这里:
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);
};
}
最佳答案
你有游戏状态变量。如果要存储多个状态,则只需要一维数组。这是样品。
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 */
关于c - 将结构数组复制到共享内存中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35507687/