Elaborato_SO/src/custom_sig.c

122 lines
3.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <custom_sig.h>
#include <structures.h>
#include <errExit.h>
#include <custom_msgq.h>
#include <custom_sem.h>
#include <custom_shm.h>
#include <forza4.h>
pid_t _PIDS[2];
void setSignal(int sig);
void sigIntHandler2(int sig) {
kill(getpid(), SIGTERM);
}
void sigHandlerServer(int sig) {
// if (sig == SIGINT) { // FIXME: non riesco a farlo funzionare, quando premo ctr+c è come se gli arrivasse al server la mossa di un giocatore
// UPDATE: funzia ma è piu bella la mia sol?
// sigint_count--;
// if (sigint_count > 0) {
// printf(PSERVER "Press again Ctrl^C to exit ");
// printf("(whitin %d sec)\n", TIME_TO_RESET);
// alarm(TIME_TO_RESET);
// } else {
// alarm(0); // toglie l'allarme
// sig = SIGTERM;
// }
// }
// if (sig == SIGALRM) {
// printf(PSERVER "");
// printf("Time to exit (%d sec) expired", TIME_TO_RESET);
// sigint_count = 2;
// }
if (sig == SIGINT) {
printf(PSERVER "Press again Ctrl^C to exit (whitin %d sec)\n", TIME_TO_RESET);
signal(SIGINT, sigIntHandler2);
alarm(TIME_TO_RESET);
}
if (sig == SIGALRM) {
printf(PSERVER "Time to exit (%d sec) expired\n", TIME_TO_RESET);
signal(SIGINT, sigHandlerServer);
}
if (sig == SIGTERM || sig == SIGHUP) {
if (_PIDS[0] > 0) {
printf(PSERVER "Terminating player one\n");
kill(_PIDS[0], SIGTERM);
}
if (_PIDS[1] > 0) {
printf(PSERVER "Terminating player two\n");
kill(_PIDS[1], SIGTERM);
}
// msgq
if (_MSGQID) {
printf(PSERVER "Deleting msg\n");
if (msgctl(_MSGQID, IPC_RMID, NULL) == -1) { //TODO: funzioni
errExit("msgctl", "sigHandlerServer");
}
}
// sem
if (_SEMID) {
printf(PSERVER "Deleting sem\n");
if (semctl(_SEMID, 0, IPC_RMID, 0) == -1) {
errExit("semctl", "sigHandlerServer");
}
}
// shm
if (_BOARD) {
printf(PSERVER "Detathing shm\n");
if (shmdt(_BOARD) == -1) {
errExit("shmdt", "sigHandlerServer");
}
}
if (_SHMID){
printf(PSERVER "Deleting shm\n");
if (shmctl(_SHMID, IPC_RMID, NULL) == -1) {
errExit("shmctl", "SigHandlerSever");
}
}
exit(0);
}
}
void setupServerSignalHandler() {
sigset_t mySet;
sigfillset(&mySet);
sigdelset(&mySet, SIGINT);
sigdelset(&mySet, SIGTERM);
sigdelset(&mySet, SIGHUP);
sigdelset(&mySet, SIGALRM);
sigprocmask(SIG_SETMASK, &mySet, NULL);
setSignal(SIGINT);
setSignal(SIGTERM);
setSignal(SIGHUP);
setSignal(SIGALRM);
}
void setSignal(int sig) {
if (signal(sig, sigHandlerServer) == SIG_ERR) {
errExit("signal", "f4Server");
}
}