-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpilot.c
100 lines (80 loc) · 3.37 KB
/
pilot.c
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
#include "global.h"
#define VALID_ATIS "ATIS"
#define VALID_LGT 4
#define MAX_TRY 10
#define WAIT_RETRY 1
void pilot_cleanup(int, int, int) __attribute__((noreturn));
int main(void) {
int server = -1;
int out_server = -1;
int not_received = -1;
int total_nak = 0;
char request[MSG_SIZE];
char buf[MSG_SIZE];
char response[MSG_SIZE];
int responseSize = 0;
memcpy(request, PILOT_REQUEST, MSG_SIZE);
if((server = open(FIFO_FILE, O_WRONLY)) == FAIL) {
printf(RED"Server seems to be down...\n"NOR);
} else {
printf("Sending REQUEST...\n");
if (write(server, request, sizeof(request)) == FAIL) {
printf("Failed to write message\n");
pilot_cleanup(server, out_server, FAIL);
} else {
if ((out_server = open(FIFO_FILE_OUT, O_RDONLY)) == FAIL) {
printf("Couldn't open output file...\n");
pilot_cleanup(server, out_server, FAIL);
} else {
while (not_received) {
responseSize = (int)read(out_server, buf, sizeof(buf));
if (responseSize == FAIL) {
printf("Failed to read response from output fifo\n");
pilot_cleanup(server, out_server, FAIL);
} else {
memcpy(response, buf, responseSize);
if (memcmp(response, VALID_ATIS, VALID_LGT) == 0) {
printf("Got response ! => %s\n", response);
if (write(server, ACK, sizeof(ACK)) == FAIL) {
printf("Failed to send ACK");
}
not_received = 0;
} else {
if (total_nak == MAX_TRY) {
printf(RED"ERROR : "NOR);
printf("Server seems unable to treat requests"
" anymore, quitting... \n");
pilot_cleanup(server, out_server, EXIT_FAILURE);
} else {
printf(RED"ERROR : %s\n"NOR, response);
printf("Sending NAK to the serveur, asking for"
" ATIS again... \n");
if (write(server, NAK, sizeof(NAK)) == FAIL) {
printf("FAILED to send NAK");
}
total_nak++;
sleep(WAIT_RETRY);
}
}
}
}
}
}
pilot_cleanup(server, out_server, EXIT_SUCCESS);
}
}
void pilot_cleanup(int in_serv, int out_serv, int status) {
if (in_serv != FAIL) {
if (close(in_serv) == FAIL) {
printf("Couldn't close input file descriptor %d\n", in_serv);
exit(status);
}
}
if (out_serv != FAIL) {
if (close(out_serv) == FAIL) {
printf("Couldn't close output file descriptor %d\n", out_serv);
exit(status);
}
}
exit(EXIT_SUCCESS);
}