-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_main.cpp
1472 lines (1201 loc) · 41.5 KB
/
test_main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include<iostream>
#include "goldchase.h"
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <functional>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/mman.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/types.h>
#include "Map.h"
#include <cstring>
#include <signal.h>
#include <mqueue.h>
#include<cstring>
#include <cstdio>
#include <errno.h>
#include <cstdlib>
#include <sstream>
#include "fancyRW.h"
using namespace std;
// uncomment before multi-node
#ifndef SHM_CONSTANTS
#define SHM_CONSTANTS
#define SHM_SM_NAME "/PD_semaphore"
#define SHM_NAME "/PD_SharedMemory"
#define MSG_QUEUE_PREFIX "/PD_MSG_QUEUE_P"
#define PORT "42425" //change this # between 2000-65k before using
#define PORT1 "42426" //change this # between 2000-65k before using
#endif
#define REAL_GOLD_MESSAGE "You found Real Gold!!"
#define FAKE_GOLD_MESSAGE "You found Fool's Gold!!"
#define EMPTY_MESSAGE_PLAYER_MOVED "m"
#define EMPTY_MESSAGE_PLAYER_NOT_MOVED "n"
#define YOU_WON_MESSAGE "You Won!"
#define CLIENT_LOG_DIR "/tmp/gchase_client.log"
#define SERVER_LOG_DIR "/tmp/gchase_server.log"
struct mapboard{
int rows;
int cols;
pid_t player_pids[5];
int daemonID;
unsigned char map[0];
};
void invoke_in_Daemon( void (*f) (string), string);
void init_Server_Daemon(string);
void init_Client_Daemon(string);
vector< char > perform_IPC_with_server(FILE *fp, int & rows, int & cols, string ip_address);
void perform_IPC_with_client(FILE *fp);
void send_Socket_Message(char PLR_MASK, string msg);
void send_Socket_Player(char PLR_MASK);
void send_Socket_Map(vector< pair<short, char> > mapChangesVector);
void socket_Communication_Handler(FILE *fp);
void process_Socket_Message(FILE *fp, char protocol_type);
void process_Socket_Player(FILE *fp, char protocol_type);
void process_Socket_Map(FILE *fp, char protocol_type);
void handleGameExit(int);
void sendSignalToActivePlayers(mapboard * mbp, int signal_enum);
void sendSignalToActivePlayersOnNode(mapboard * mbp, int signal_enum);
void sendSignalToDaemon(mapboard * mbp, int signal_enum);
void initializeMsgQueue(int thisPlayer);
void initializeMsgQueueInDaemon(int thisPlayer);
void sendMsgFromDaemonToPlayer(int toPlayerInt, string msg);
Map * gameMap = NULL;
mqd_t readqueue_fd; //message queue file descriptor
string mq_name;
sem_t* shm_sem;
mapboard * mbp = NULL;
int thisPlayer = 0, thisPlayerLoc= 0;
char initial_map[2100];
int write_fd = -1;
int read_fd = -1;
mqd_t daemon_readqueue_fds[5]; //message queue file descriptor in daemon
string daemon_mq_names[5];
mapboard * initSharedMemory(int rows, int columns){
int fd, size;
mapboard * mbp;
fd = shm_open(SHM_NAME,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
size = (rows*columns + sizeof(mapboard));
ftruncate(fd, size);
mbp = (mapboard*) mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
return mbp;
}
mapboard * readSharedMemory(){
int fd, size, rows, columns;
mapboard * mbp;
fd = shm_open(SHM_NAME,O_RDWR, S_IRUSR|S_IWUSR);
read(fd,&rows,sizeof(int));
read(fd,&columns,sizeof(int));
size = (rows*columns + sizeof(mapboard));
ftruncate(fd, size);
mbp = (mapboard*) mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
return mbp;
}
vector<vector< char > > readMapFromFile(char * mapFile, int &golds){
vector<vector< char > > mapVector;
vector< char > temp;
string line;
char c;
ifstream mapStream(mapFile);
mapStream >>golds;
mapStream.get(c);
while(getline(mapStream,line))
{
for(int i=0; i < line.length(); i++){
temp.push_back(line[i]);
}
mapVector.push_back(temp);
temp.clear();
}
return mapVector;
}
void initGameMap(mapboard * mbp, vector<vector< char > > mapVector ){
unsigned char * mp;
mp = mbp->map;
for(unsigned i=0;i<mapVector.size();i++){
for(unsigned j=0;j<mapVector[i].size();j++){
if(mapVector[i][j]==' ')
*mp=0;
else if(mapVector[i][j]== '*')
*mp=G_WALL;
mp++;
}
}
return;
}
int placeElementOnMap(mapboard * mbp, int elem){
srand(time(NULL));
int pos, total_pos = mbp->rows * mbp->cols;
while(1){
pos = rand() % total_pos;
//cout<<"rand "<<pos<<endl;
if(mbp->map[pos] == G_WALL)
continue;
if(mbp->map[pos] == G_GOLD)
continue;
if(mbp->map[pos] == G_FOOL)
continue;
if(mbp->map[pos] == G_PLR0)
continue;
if(mbp->map[pos] == G_PLR1)
continue;
if(mbp->map[pos] == G_PLR2)
continue;
if(mbp->map[pos] == G_PLR3)
continue;
if(mbp->map[pos] == G_PLR4)
continue;
mbp->map[pos] = elem;
break;
}
return pos;
}
void placeGoldsOnMap(mapboard * mbp, int goldCount){
if(goldCount > 0)
placeElementOnMap(mbp, G_GOLD);
for(int i= 0; i< (goldCount-1) ; i++)
placeElementOnMap(mbp, G_FOOL);
return;
}
int placeIncrementPlayerOnMap(mapboard * mbp,int & thisPlayerLoc){
int thisPlayer = -1;
if(mbp->player_pids[0] == -1 ){
mbp->player_pids[0] = getpid();
thisPlayer = G_PLR0;
}
else if(mbp->player_pids[1] == -1 ){
mbp->player_pids[1] = getpid();
thisPlayer = G_PLR1;
}
else if(mbp->player_pids[2] == -1 ){
mbp->player_pids[2] = getpid();
thisPlayer = G_PLR2;
}
else if(mbp->player_pids[3] == -1 ){
mbp->player_pids[3] = getpid();
thisPlayer = G_PLR3;
}
else if(mbp->player_pids[4] == -1 ){
mbp->player_pids[4] = getpid();
thisPlayer = G_PLR4;
}
thisPlayerLoc = placeElementOnMap(mbp, thisPlayer);
return thisPlayer;
}
bool isCurrentMoveOffMap(mapboard * mbp, int currentPos , int nextPos){
unsigned char * mp;
mp = mbp->map;
int rows = mbp->rows, cols = mbp->cols;
if(currentPos < cols && nextPos < 0)
return true;
if( currentPos / cols == rows - 1 && nextPos >= rows * cols)
return true;
if( currentPos % cols == 0 && nextPos == currentPos -1 )
return true;
if( currentPos % cols == cols - 1 && nextPos == currentPos + 1)
return true;
return false;
}
bool isCurrentMoveValid(mapboard * mbp, int currentPos , int nextPos){
unsigned char * mp;
mp = mbp->map;
int rows = mbp->rows, cols = mbp->cols;
if(currentPos < cols && nextPos < 0)
return false;
if( currentPos / cols == rows - 1 && nextPos >= rows * cols)
return false;
if( currentPos % cols == 0 && nextPos == currentPos -1 )
return false;
if( currentPos % cols == cols - 1 && nextPos == currentPos + 1)
return false;
if(mp[nextPos] == G_WALL)
return false;
else
return true;
}
const char * performGoldCheck(mapboard * mbp, int currentPos, bool & thisPlayerFoundGold){
const char * realGoldMessage = REAL_GOLD_MESSAGE;
const char * fakeGoldMessage = FAKE_GOLD_MESSAGE;
const char * emptyMessage = EMPTY_MESSAGE_PLAYER_MOVED;
unsigned char * mp;
mp = mbp->map;
if(mp[currentPos] & G_GOLD)
{
thisPlayerFoundGold = true;
mp[currentPos] &= ~G_GOLD;
return realGoldMessage;
}
else if(mp[currentPos] & G_FOOL)
return fakeGoldMessage;
else
return emptyMessage;
}
const char * processPlayerMove(mapboard * mbp, int & thisPlayerLoc, int thisPlayer, int keyInput, bool & thisPlayerFoundGold, bool & thisQuitGameloop){
unsigned char * mp;
const char * emptyMessage = EMPTY_MESSAGE_PLAYER_NOT_MOVED;
const char * youWonMessage = YOU_WON_MESSAGE;
bool quitGameLoop = false;
mp = mbp->map;
int nextPos = 0, cols = mbp->cols, goldCheck = -1;
switch (keyInput) {
case 108: // key l move right
nextPos = thisPlayerLoc + 1;
break;
case 104: // key h move left
nextPos = thisPlayerLoc - 1;
break;
case 107: // key k move up
nextPos = thisPlayerLoc - cols;
break;
case 106: // key j move down
nextPos = thisPlayerLoc + cols ;
break;
}
if((thisPlayerFoundGold) && isCurrentMoveOffMap(mbp, thisPlayerLoc, nextPos) ){
thisQuitGameloop = true;
return youWonMessage;
}
if(isCurrentMoveValid(mbp, thisPlayerLoc, nextPos) ){
mp[thisPlayerLoc] &= ~thisPlayer;
thisPlayerLoc = nextPos;
mp[thisPlayerLoc] |= thisPlayer;
return performGoldCheck(mbp, thisPlayerLoc, thisPlayerFoundGold);
}
return emptyMessage;
}
bool isGameBoardEmpty(mapboard * mbp){
if (mbp->player_pids[0] == -1 && mbp->player_pids[1] == -1 && mbp->player_pids[2] == -1 && mbp->player_pids[3] == -1 && mbp->player_pids[4] == -1)
return true;
else
return false;
}
int getPlayerFromMask(int pMask){
if(pMask & G_PLR0) return 0;
else if (pMask & G_PLR1) return 1;
else if (pMask & G_PLR2) return 2;
else if (pMask & G_PLR3) return 3;
else if (pMask & G_PLR4) return 4;
else return -1;
}
unsigned int getActivePlayersMask(){
unsigned int mask = 0;
if(mbp->player_pids[0] != -1 ){
mask |= G_PLR0;
}
if(mbp->player_pids[1] != -1 ){
mask |= G_PLR1;
}
if(mbp->player_pids[2] != -1 ){
mask |= G_PLR2;
}
if(mbp->player_pids[3] != -1 ){
mask |= G_PLR3;
}
if(mbp->player_pids[4] != -1 ){
mask |= G_PLR4;
}
return mask;
}
string itos_utility(int i){
std::stringstream out;
out << i;
return out.str();
}
vector< char > perform_IPC_with_server(FILE *fp, int & rows, int & cols, string ip_address){
int sockfd, status; //file descriptor for the socket
const char* portno= PORT;
char * ip_cstr = new char[ip_address.length()+1];
strcpy(ip_cstr, ip_address.c_str());
struct addrinfo hints;
memset(&hints, 0, sizeof(hints)); //zero out everything in structure
hints.ai_family = AF_UNSPEC; //don't care. Either IPv4 or IPv6
hints.ai_socktype=SOCK_STREAM; // TCP stream sockets
struct addrinfo *servinfo;
//instead of "localhost", it could by any domain name
if((status=getaddrinfo(ip_cstr, portno, &hints, &servinfo))==-1)
{fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));exit(1);}
sockfd=socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if((status=connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen))==-1)
{perror("connect");exit(1);}
//release the information allocated by getaddrinfo()
freeaddrinfo(servinfo);
fprintf(fp, "Connected to server.\n");
char initial_map[2100];
READ<int>(sockfd, &rows, sizeof(int));
READ<int>(sockfd, &cols, sizeof(int));
vector< char > mbpVector(rows*cols , '*');
fprintf(fp, "reading from server done. rows - %d cols - %d\n", rows,cols);
READ<char>(sockfd, initial_map, (rows*cols + 1)*sizeof(char));
for (int i=0; i < rows*cols; i++)
mbpVector[i] = initial_map[i];
fprintf(fp, "reading from server done map - %s\n", initial_map);
read_fd = sockfd;
delete [] ip_cstr;
//close(sockfd);
return mbpVector;
}
void perform_IPC_with_client(FILE *fp){
int sockfd, status, rows, cols, iter = 0; //file descriptor for the socket
const char* portno = PORT;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints)); //zero out everything in structure
hints.ai_family = AF_UNSPEC; //don't care. Either IPv4 or IPv6
hints.ai_socktype=SOCK_STREAM; // TCP stream sockets
hints.ai_flags=AI_PASSIVE; //file in the IP of the server for me
struct addrinfo *servinfo;
if((status=getaddrinfo(NULL, portno, &hints, &servinfo))==-1)
{fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));exit(1);}
sockfd=socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
/*avoid "Address already in use" error*/
int yes=1;
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))==-1)
{perror("setsockopt");exit(1);}
//We need to "bind" the socket to the port number so that the kernel
//can match an incoming packet on a port to the proper process
if((status=bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen))==-1)
{perror("bind");exit(1);}
//when done, release dynamically allocated memory
freeaddrinfo(servinfo);
if(listen(sockfd,1)==-1)
{perror("listen");exit(1);}
fprintf(fp, "Blocking, waiting for client to connect\n");
struct sockaddr_in client_addr;
socklen_t clientSize=sizeof(client_addr);
int new_sockfd;
if((new_sockfd=accept(sockfd, (struct sockaddr*) &client_addr, &clientSize))==-1)
{perror("accept");exit(1);}
fprintf(fp, "Connected to client.\n");
rows = mbp->rows;
cols = mbp->cols;
for (int i=0; i < rows*cols; i++)
initial_map[i] = mbp->map[i];
WRITE<int>(new_sockfd, &rows, sizeof(int));
WRITE<int>(new_sockfd, &cols, sizeof(int));
WRITE<char>(new_sockfd, initial_map, (rows*cols + 1)*sizeof(char));
fprintf(fp, "Writing to client completed.\n");
write_fd = new_sockfd;
//close(new_sockfd);
}
int get_Read_Socket_fd(FILE * fp){
int sockfd; //file descriptor for the socket
int status; //for error checking
fprintf(fp, "Attempting to get Read Socket fd for Socket protocol IPC.\n");
fflush(fp);
//change this # between 2000-65k before using
const char* portno = PORT1;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints)); //zero out everything in structure
hints.ai_family = AF_UNSPEC; //don't care. Either IPv4 or IPv6
hints.ai_socktype=SOCK_STREAM; // TCP stream sockets
hints.ai_flags=AI_PASSIVE; //file in the IP of the server for me
struct addrinfo *servinfo;
if((status=getaddrinfo(NULL, portno, &hints, &servinfo))==-1)
{
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
sockfd=socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
/*avoid "Address already in use" error*/
int yes=1;
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))==-1)
{
perror("setsockopt");
exit(1);
}
//We need to "bind" the socket to the port number so that the kernel
//can match an incoming packet on a port to the proper process
if((status=bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen))==-1)
{
perror("bind");
exit(1);
}
//when done, release dynamically allocated memory
freeaddrinfo(servinfo);
if(listen(sockfd,1)==-1)
{
perror("listen");
exit(1);
}
fprintf(fp, "Blocking, waiting for client to connect\n");
fflush(fp);
struct sockaddr_in client_addr;
socklen_t clientSize=sizeof(client_addr);
int new_sockfd;
if((new_sockfd=accept(sockfd, (struct sockaddr*) &client_addr, &clientSize))==-1)
{
perror("accept");
exit(1);
}
fprintf(fp, "Connected to client.\n");
fprintf(fp, "returning Read Socket fd for Socket protocol IPC as %d.\n",new_sockfd);
return new_sockfd;
}
int get_Write_Socket_fd(FILE * fp, string ip_address){
int sockfd; //file descriptor for the socket
int status; //for error checking
fprintf(fp, "Attempting to get Write Socket fd for Socket protocol IPC.\n");
fflush(fp);
//change this # between 2000-65k before using
const char* portno = PORT1;
char * ip_cstr = new char[ip_address.length()+1];
strcpy(ip_cstr, ip_address.c_str());
struct addrinfo hints;
memset(&hints, 0, sizeof(hints)); //zero out everything in structure
hints.ai_family = AF_UNSPEC; //don't care. Either IPv4 or IPv6
hints.ai_socktype=SOCK_STREAM; // TCP stream sockets
struct addrinfo *servinfo;
//instead of "localhost", it could by any domain name
if((status=getaddrinfo(ip_cstr, portno, &hints, &servinfo))==-1)
{
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
sockfd=socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if((status=connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen))==-1)
{
perror("connect");
exit(1);
}
//release the information allocated by getaddrinfo()
freeaddrinfo(servinfo);
delete [] ip_cstr;
fprintf(fp, "Connected to server.\n");
fprintf(fp, "returning Write Socket fd for Socket protocol IPC as %d.\n", sockfd);
return sockfd;
}
void long_sleep(){
sleep(30);
}
void send_Socket_Player(char PLR_MASK){
char protocol_type = G_SOCKPLR;
protocol_type |= PLR_MASK;
WRITE <char>(write_fd, &protocol_type, sizeof(char));
return;
}
void socket_Player_signal_handler(int){
char plr_mask = getActivePlayersMask();
send_Socket_Player(plr_mask);
}
void send_Socket_Message(char PLR_MASK, string msg){
int msg_length = msg.length() + 1;
char protocol_type = G_SOCKMSG;
char *cstr = new char[msg_length];
strcpy(cstr, msg.c_str());
protocol_type |= PLR_MASK;
printf("in client : msglen %d - msg - %s\n",msg_length, cstr);
WRITE <char>(write_fd, &protocol_type, sizeof(char));
WRITE <int>(write_fd, &msg_length, sizeof(int));
WRITE <char>(write_fd, cstr, msg_length*sizeof(char));
delete [] cstr;
}
string receiveMessagebyDaemon(mqd_t read_fd){
int err;
char msg[251]; //a char array for the message
memset(msg, 0, 251); //zero it out (if necessary)
string msg_str = "";
struct sigevent mq_notification_event;
mq_notification_event.sigev_notify=SIGEV_SIGNAL;
mq_notification_event.sigev_signo=SIGUSR2;
mq_notify(read_fd, &mq_notification_event);
while((err=mq_receive(read_fd, msg, 250, NULL))!=-1)
{
msg_str = msg;
//call postNotice(msg) for your Map object;
//cout << "Message received: " << msg << endl;
memset(msg, 0, 251);//set all characters to '\0'
}
//we exit while-loop when mq_receive returns -1
//if errno==EAGAIN that is normal: there is no message waiting
if(errno!=EAGAIN)
{
perror("mq_receive");
}
return msg_str;
}
void socket_Message_signal_handler(int){
char p_mask = G_SOCKMSG;
string msg_str;
for(int i = 0; i<5;i++){
if (daemon_readqueue_fds[i] != -1){
msg_str = receiveMessagebyDaemon(daemon_readqueue_fds[i]);
if(msg_str != "" && i == 0){
send_Socket_Message(p_mask | G_PLR0, msg_str);
}
if(msg_str != "" && i == 1){
send_Socket_Message(p_mask | G_PLR1, msg_str);
}
if(msg_str != "" && i == 2){
send_Socket_Message(p_mask | G_PLR2, msg_str);
}
if(msg_str != "" && i == 3){
send_Socket_Message(p_mask | G_PLR3, msg_str);
}
if(msg_str != "" && i == 4){
send_Socket_Message(p_mask | G_PLR4, msg_str);
}
}
} // end of for
}
void send_Socket_Map(vector<pair<short,char> > mapChangesVector){
char protocol_type = 0, changedMapValue;
short changedMapId;
int Vector_size = mapChangesVector.size();
WRITE <char>(write_fd, &protocol_type, sizeof(char));
WRITE <int>(write_fd, &Vector_size, sizeof(int));
for(int i = 0; i<Vector_size; i++){
changedMapId = mapChangesVector[i].first;
changedMapValue = mapChangesVector[i].second;
WRITE <short>(write_fd, &changedMapId, sizeof(short));
WRITE <char>(write_fd, &changedMapValue, sizeof(char));
}
}
void socket_Map_signal_handler(int){
int rows, cols;
vector<pair<short,char> > mapChangesVector;
rows = mbp->rows;
cols = mbp->cols;
for (int i=0; i < rows*cols; i++){
if(initial_map[i] != mbp->map[i]){
mapChangesVector.push_back(make_pair(i, mbp->map[i] ));
initial_map[i] = mbp->map[i];
}
}
if(mapChangesVector.size() > 0){
send_Socket_Map(mapChangesVector);
}
}
void process_Socket_Message(FILE *fp, char active_plr_mask){
int msg_length = 0, toPlayerInt;
char msg_cstring[100];
READ <int>(read_fd, &msg_length, sizeof(int));
READ <char>(read_fd, msg_cstring, msg_length*sizeof(char));
fprintf(fp, "in process_Socket_Message : msglen %d - msg - %s\n",msg_length, msg_cstring);
string msg(msg_cstring);
for(int i = 0; i < 5;i++ ){
if(i==0 && (active_plr_mask & G_PLR0) ){
fprintf(fp, "sending Message to Player %d", i+1);
sendMsgFromDaemonToPlayer(i, msg);
}
if(i==1 && (active_plr_mask & G_PLR1) ){
fprintf(fp, "sending Message to Player %d", i+1);
sendMsgFromDaemonToPlayer(i, msg);
}
if(i==2 && (active_plr_mask & G_PLR2) ){
fprintf(fp, "sending Message to Player %d", i+1);
sendMsgFromDaemonToPlayer(i, msg);
}
if(i==3 && (active_plr_mask & G_PLR3) ){
fprintf(fp, "sending Message to Player %d", i+1);
sendMsgFromDaemonToPlayer(i, msg);
}
if(i==4 && (active_plr_mask & G_PLR4) ){
fprintf(fp, "sending Message to Player %d", i+1);
sendMsgFromDaemonToPlayer(i, msg);
}
}//end of for loop
}
void process_Socket_Player(FILE *fp, char protocol_type){
fprintf(fp, "in process_Socket_Player %d\n",protocol_type);
sem_wait(shm_sem);
for(int i = 0; i < 5;i++ ){
if(i==0 && (protocol_type & G_PLR0) && mbp->player_pids[i] == -1){ // p1 joined
fprintf(fp, "player 1 found\n");
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if(i==0 && !(protocol_type & G_PLR0) && mbp->player_pids[i] != -1){ // p1 left
fprintf(fp, "player 1 Left\n");
mbp->player_pids[i] = -1;
mq_close(daemon_readqueue_fds[i]);
mq_unlink(daemon_mq_names[i].c_str());
daemon_readqueue_fds[i] = -1;
}
if ( i==1 && (protocol_type & G_PLR1) && mbp->player_pids[i] == -1){ // p2 joined
fprintf(fp, "player 2 found\n");
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if(i==1 && !(protocol_type & G_PLR1) && mbp->player_pids[i] != -1){ // p2 left
fprintf(fp, "player 2 Left\n");
mbp->player_pids[i] = -1;
mq_close(daemon_readqueue_fds[i]);
mq_unlink(daemon_mq_names[i].c_str());
daemon_readqueue_fds[i] = -1;
}
if ( i==2 && (protocol_type & G_PLR2) && mbp->player_pids[i] == -1){ // p3 joined
fprintf(fp, "player 3 found\n");
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if(i==2 && !(protocol_type & G_PLR2) && mbp->player_pids[i] != -1){ // p3 left
fprintf(fp, "player 3 Left\n");
mbp->player_pids[i] = -1;
mq_close(daemon_readqueue_fds[i]);
mq_unlink(daemon_mq_names[i].c_str());
daemon_readqueue_fds[i] = -1;
}
if ( i==3 && (protocol_type & G_PLR3) && mbp->player_pids[i] == -1){ // p4 joined
fprintf(fp, "player 4 found\n");
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if(i==3 && !(protocol_type & G_PLR3) && mbp->player_pids[i] != -1){ // p4 left
fprintf(fp, "player 4 Left\n");
mbp->player_pids[i] = -1;
mq_close(daemon_readqueue_fds[i]);
mq_unlink(daemon_mq_names[i].c_str());
daemon_readqueue_fds[i] = -1;
}
if ( i==4 && (protocol_type & G_PLR4) && mbp->player_pids[i] == -1){
fprintf(fp, "player 5 found\n");
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if(i==4 && !(protocol_type & G_PLR4) && mbp->player_pids[i] != -1){ // p5 left
fprintf(fp, "player 5 Left\n");
mbp->player_pids[i] = -1;
mq_close(daemon_readqueue_fds[i]);
mq_unlink(daemon_mq_names[i].c_str());
daemon_readqueue_fds[i] = -1;
}
}// end of for loop
sem_post(shm_sem);
if(protocol_type == -128 ){
fprintf(fp, "No active players left in Game.\n");
fflush(fp);
//socket_break_Read_signal_handler();
char protocol_type1 = 1;
WRITE <char>(write_fd, &protocol_type1, sizeof(char));
}
}
void process_Socket_Map(FILE *fp, char protocol_type){
int Vector_size;
char changedMapValue;
short changedMapId;
vector<pair<short,char> > mapChangesVector;
READ <int>(read_fd, &Vector_size, sizeof(int));
fprintf(fp, "in server : Vector_size %d\n",Vector_size);
for (int i=0; i<Vector_size; i++){
READ <short>(read_fd, &changedMapId, sizeof(short));
READ <char>(read_fd, &changedMapValue, sizeof(char));
mapChangesVector.push_back(make_pair(changedMapId,changedMapValue));
}
sem_wait(shm_sem);
for(int i = 0; i<Vector_size; i++){
mbp->map[mapChangesVector[i].first] = mapChangesVector[i].second;
}
sem_post(shm_sem);
sendSignalToActivePlayersOnNode(mbp, SIGUSR1);
}
void socket_Communication_Handler(FILE *fp){
char protocol_type = ' ' ; int return_code;
fprintf(fp, "Attempting to start Socket communications protocol\n");
return_code = READ <char>(read_fd, &protocol_type, sizeof(char));
if(return_code == -1){
fprintf(fp, "Attempting to start Socket returned error Code -1.\n");
fflush(fp);
}
if (protocol_type&G_SOCKPLR ){
fprintf(fp, "read protocol_type - Socket_Player from client.\n");
process_Socket_Player(fp, protocol_type);
}
else if (protocol_type&G_SOCKMSG ){
fprintf(fp, "read protocol_type - Socket_Message from client.\n");
process_Socket_Message(fp, protocol_type);
}
else if (protocol_type == 0 ){
fprintf(fp, "read protocol_type - Socket_Map from client.\n");
process_Socket_Map(fp, protocol_type);
}
else if (protocol_type == 1 ){
fprintf(fp, "read protocol_type - break for Blocking read.\n");
char protocol_type1 = 2;
WRITE <char>(write_fd, &protocol_type1, sizeof(char));
fprintf(fp,"All done in demon, Killing daemon with pid -%d now.\n", getpid());
close(write_fd);
close(read_fd);
fclose(fp);
exit(0);
}
else if (protocol_type == 2 ){
fprintf(fp, "read protocol_type - break for Blocking read.\n");
fprintf(fp,"Cleaning up SHM and semaphore in Daemon.\n", getpid());
fflush(fp);
shm_unlink(SHM_NAME);
sem_close(shm_sem);
sem_unlink(SHM_SM_NAME);
fprintf(fp,"All done in demon, Killing daemon with pid -%d now.\n", getpid());
close(write_fd);
close(read_fd);
fclose(fp);
exit(0);
}
}
void setUpDaemonSignalHandlers(){
struct sigaction exit_action;
exit_action.sa_handler = socket_Player_signal_handler;
exit_action.sa_flags=0;
sigemptyset(&exit_action.sa_mask);
sigaction(SIGHUP, &exit_action, NULL);
struct sigaction my_sig_handler;
my_sig_handler.sa_handler = socket_Map_signal_handler;
sigemptyset(&my_sig_handler.sa_mask);
my_sig_handler.sa_flags=0;
sigaction(SIGUSR1, &my_sig_handler, NULL);
struct sigaction action_to_take;
//action_to_take.sa_handler=read_message;
action_to_take.sa_handler=socket_Message_signal_handler;
sigemptyset(&action_to_take.sa_mask);
action_to_take.sa_flags=0;
sigaction(SIGUSR2, &action_to_take, NULL);
}
void init_Server_Daemon(string ip_address){
int rows, cols;
FILE * fp = fopen (SERVER_LOG_DIR, "w+");
fprintf(fp, "Logging info from daemon with pid : %d\n", getpid());
fflush(fp);
setUpDaemonSignalHandlers();
sem_wait(shm_sem);
mbp = readSharedMemory();
rows = mbp->rows;
cols = mbp->cols;
for (int i=0; i < rows*cols; i++)
initial_map[i] = mbp->map[i];
initial_map[rows*cols] = '\0';
fprintf(fp, "readSharedMemory done. rows - %d cols - %d\n", rows, cols);
fflush(fp);
daemon_readqueue_fds[0] = -1;daemon_readqueue_fds[1] = -1;daemon_readqueue_fds[2] = -1;daemon_readqueue_fds[3] = -1;daemon_readqueue_fds[4] = -1;
mbp->daemonID = getpid();
sem_post(shm_sem);
perform_IPC_with_client(fp);
char active_plr_mask = getActivePlayersMask();
WRITE <char>(write_fd, &active_plr_mask, sizeof(char));
read_fd = get_Read_Socket_fd(fp);
fflush(fp);
fprintf(fp, "Entering infinite loop with blocking read now.\n");
fflush(fp);
while(1){
socket_Communication_Handler(fp); // takes care of read_fd and exit
//sleep(1);
}
}
void intialize_active_plr_client(char active_plr_mask){
for(int i = 0; i < 5;i++ ){
if(i==0 && (active_plr_mask & G_PLR0) && mbp->player_pids[i] == -1){
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if ( i==1 && (active_plr_mask & G_PLR1) && mbp->player_pids[i] == -1){
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if ( i==2 && (active_plr_mask & G_PLR2) && mbp->player_pids[i] == -1){
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if ( i==3 && (active_plr_mask & G_PLR3) && mbp->player_pids[i] == -1){
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
if ( i==4 && (active_plr_mask & G_PLR4) && mbp->player_pids[i] == -1){
mbp->player_pids[i] = getpid();
initializeMsgQueueInDaemon(i);
}
}
}
void init_Client_Daemon(string ip_address){
int rows, cols, goldCount, fd;
daemon_readqueue_fds[0] = -1;daemon_readqueue_fds[1] = -1;daemon_readqueue_fds[2] = -1;daemon_readqueue_fds[3] = -1;daemon_readqueue_fds[4] = -1;
FILE * fp = fopen (CLIENT_LOG_DIR, "w+");
fprintf(fp, "Logging info from daemon with pid : %d\n", getpid());
fprintf(fp, "Received IP Address as : %s\n", ip_address.c_str());
fprintf(fp,"Attempting ClientDaemon Initialize IPC now.\n");