From 7bea27b8e755a02526183477efb3b16db9d4c290 Mon Sep 17 00:00:00 2001 From: Edi De Candido Date: Sun, 14 May 2023 22:13:55 +0200 Subject: [PATCH] shared memory finita --- inc/structures.h | 17 +++++++++++------ src/custom_shm.c | 37 +++++++++++++++++++++++++++++++++---- 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/inc/structures.h b/inc/structures.h index ef22c7e..642c1f4 100644 --- a/inc/structures.h +++ b/inc/structures.h @@ -3,7 +3,6 @@ -#define KEYFILE "../LICENSE" // semaphore union semun { @@ -13,6 +12,9 @@ union semun { }; // shared memory +#define KEYFILE "../LICENSE" +#define SHMERR (void *)-1 + typedef struct { int collums; int rows; @@ -26,15 +28,18 @@ typedef enum { PLAYER2 } tile_t; -typedef struct { - tile_t *board; - input_server_t inS; -} shm_t; - static const size_t SHM_SIZE = sizeof(shm_t); // signal #define DEFAULT_SIGINT 2 #define TIME_TO_RESET 10 +//message queue +typedef struct { + long mtype; + int board_id; + input_server_t server_in; + char *name_player1, *name_player2; +} msgq_t; + #endif \ No newline at end of file diff --git a/src/custom_shm.c b/src/custom_shm.c index a4180ff..1381b7f 100644 --- a/src/custom_shm.c +++ b/src/custom_shm.c @@ -1,16 +1,45 @@ +#include #include #include #include #include #include -int getShmid() { - int shmid = shmget(ftok(KEYFILE, 'z'), SHM_SIZE, IPC_CREAT | S_IRUSR | S_IWUSR); - if (result == -1) { +int getShmid(int row, int col) { + int shmid = shmget(ftok(KEYFILE, 'z'), row * col * sizeof(tile_t), IPC_CREAT | S_IRUSR | S_IWUSR); + if (shmid == -1) { errExit("shmget", "getShmid"); } - return shmid; } +tile_t * shmServerAt(int shmid) { + tile_t *result = (tile_t *)shmat(shmid, NULL, 0); + if (result == SHMERR) { + errExit("shmat", "shmServerAt"); + } + + return result; +} + +tile_t * shmClientAt(int shmid) { + tile_t *result = (tile_t *)shmat(shmid, NULL, SHM_RDONLY); + if (result == SHMERR) { + errExit("shmat", "shmClientAt"); + } + + return result; +} + +void shmDt(void *shm) { + if (shmdt(shm) == -1) { + errExit("shmdt", "shmDt"); + } +} + +void shmServerRm(int shmid) { + if (shmctl(shmid, IPC_RMID, NULL) == -1) { + errExit("shmctl", "shmServerRm"); + } +} \ No newline at end of file