void *handle_client(void *arg) {
int new_socket = *((int *) arg);
/* --------------------------------------------------------------------------------*/
// Receive the client request using recv() system call
char buffer[1024];
int bytes_received = recv(new_socket, buffer, 1024, 0);
if (bytes_received < 0) {
printf("Error receiving client request\n");
return NULL;
}
buffer[bytes_received] = '\0';
// Close the socket
char* message = malloc(2048*sizeof(char));
message = handle_input(buffer);
if ( message != NULL) {
// Send the message to the client
int bytes_sent = send(new_socket, message, strlen(message), 0);
if (bytes_sent < 0) {
printf("Error sending message to client\n");
}
close(new_socket);
// Mutex lock to protect the critical section
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock);
// Access the shared resources
FILE* file = fopen("server_records.txt", "a");
if (file != NULL) {
fprintf(file, "Client request: %s\nServer response: %s\n\n", buffer, message);
fclose(file);
}
pthread_mutex_unlock(&lock);
}
return NULL;
}
char* handle_input(char* data) {
int i = 1;
int k = 0;
char seat_type[50];
char number_of_seats[50];
while ( *data != ' ') {
seat_type[k++] = *(data++);
}
seat_type[k] = '\0';
data++; // Skip the ' ' character
int p = 0;
while (*data != '\n') {
number_of_seats[p++] = *(data++);
}
number_of_seats[p] = '\0';
char* msg = malloc(1024*sizeof(char));
char* file_msg = malloc(1024 * sizeof(char));
pthread_mutex_lock(&lock_file); // lock file access
FILE* file = fopen("Seat_Availability.txt", "r+");
FILE* new_file;
if (file != NULL) {
int found = 0;
char line[500], avl_seats[50];
while (fgets(line, sizeof(line), file) != NULL) {
char* token = strtok(line, " ");
if (strcmp(token, seat_type) == 0) {
token = strtok(NULL, " ");
strcpy(avl_seats, token);
found = 1;
break;
}
}
if (found) {
int required_seats = atoi(number_of_seats);
int available_seats = atoi(avl_seats);
int remaining_seats = 0;
char seats_remain[50];
if (required_seats > available_seats) {
strcpy(msg,"Required Number of Seats Not Available");
} else {
remaining_seats = available_seats - required_seats;
sprintf(seats_remain, "%d", remaining_seats);
fseek(file, -strlen(avl_seats), SEEK_CUR); // move the file pointer back to the start of the available seats value
fprintf(file, "%s", seats_remain); // overwrite the old value with the new one
fflush(file);
sprintf(msg, "%d Seats have been booked for type %s", required_seats, seat_type);
sprintf(file_msg, "FOR TYPE: %s\n%d Seats have been booked. %d Seats remaining\n\n", seat_type, required_seats, remaining_seats);
new_file = fopen("server_records.txt", "a");
if (new_file != NULL) {
fprintf(new_file, "%s", file_msg);
fclose(new_file);
}
}
} else {
strcpy(msg,"Seat type not found!");
}
}
fclose(file);
fclose(new_file);
pthread_mutex_unlock(&lock_file); // unlock file access
return msg;
}