Elaborato_SO/src/F4Server.c

113 lines
2.6 KiB
C

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <string.h>
#include <unistd.h>
#include <server.h>
#include <structures.h>
#include <custom_sem.h>
#include <custom_shm.h>
#include <errExit.h>
#include <forza4.h>
#include <custom_msgq.h>
#include <custom_sig.h>
int main(int argc, char *argv[]){
printf("Il mio pid per killarmi: %d\n", getpid()); //FIXME: TMP
setupServer(argc, argv);
// aperta semaforo per connessione dei due client
printf(PSERVER "Waiting for players...\n");
semOp(_SEMID, CLIENT0, 1);
semOp(_SEMID, CLIENT1, 1);
player_ds player;
char name[2][MAX_NAME];
// aspetto PRIMO client //FIXME: codice duplicato
semOp(_SEMID, SERVER, -1);
// ricevo nome primo client
rcvPlayer(&player);
strcpy(name[player.id], player.name_player);
_PIDS[player.id] = player.pid;
printf(PSERVER "Player %s connected\n", name[player.id]);
// aspetto SECONDO client
semOp(_SEMID, SERVER, -1);
// ricevo nome secondo client
rcvPlayer(&player);
strcpy(name[player.id], player.name_player);
_PIDS[player.id] = player.pid;
printf(PSERVER "Player %s connected\n", name[player.id]);
// avvisto inizio partita
semOp(_SEMID, CLIENT0, 1);
semOp(_SEMID, CLIENT1, 1);
// PARTITA
printf(PSERVER "Starting game\n");
int turns_left = _INPUT_S.rows * _INPUT_S.collums;
int turn = 0;
tile_t result = -1;
move_t move;
do {
//FIXME: tmp
printf("result: %d\n", result);
// apro semaforo al player di turno
semOp(_SEMID, turn, 1);
printf(PSERVER "%s's turn\n", name[turn]);
// aspetto che mi mandi una mossa
rcvMove(&move);
insertMove(move.move, turn);
// info
printf("move: %d\n", move.move);
printf("turns left: %d\n", turns_left - 1);
// dico al player che la mossa è stata effettuata per fargli stampare il campo
semOp(_SEMID, turn, 1);
// next turn
turn ^= 1;
} while (--turns_left && (result = checkWin(move.move)) == -1);
printf("result: %d\n", result);
if (result == -1) {
printf(PSERVER "Game ended in a draw\n");
} else {
printf(PSERVER "%s won\n", name[result]);
}
game_end_t game_end = {.mtype = GAME_END, .winner = result};
sndGame_end(&game_end);
sndGame_end(&game_end);
printf("%d %d\n", _PIDS[0], _PIDS[1]);
kill(_PIDS[0], SIGUSR1);
kill(_PIDS[1], SIGUSR1);
raise(SIGTERM);
}