Compare commits

...

2 commits

Author SHA1 Message Date
Daniele Lacamera
d3c0fbf8aa Fixed poll() after discard of initial message 2024-11-29 14:45:34 +00:00
Daniele Lacamera
7aace4e904 Improved cleanup on close 2024-11-29 14:07:05 +00:00

View file

@ -51,6 +51,7 @@ void clear_screen(int client_fd) {
/* Execute a git-slides command */
void execute_git_slides(const char *repo_path, const char *slide_command) {
char command[CMD_SIZE];
memset(command, 0, CMD_SIZE);
snprintf(command, sizeof(command), "cd %s && git-slides %s", repo_path, slide_command);
system(command);
}
@ -73,6 +74,19 @@ void load_slide_content(const char *slides_path, char *output) {
close(fd);
}
/* Clean up client resources */
void cleanup_client(struct Client *client) {
if (client->fd != -1) {
close(client->fd);
client->fd = -1;
}
if (strlen(client->repo_path) > 0) {
char rm_command[CMD_SIZE];
snprintf(rm_command, sizeof(rm_command), "rm -rf %s", client->repo_path);
system(rm_command);
}
}
/* Handle client input and update slides */
void handle_client_input(struct Client *client, char command) {
if (command == ' ') {
@ -81,8 +95,7 @@ void handle_client_input(struct Client *client, char command) {
execute_git_slides(client->repo_path, "prev");
} else if (command == 'q') {
clear_screen(client->fd);
close(client->fd);
client->fd = -1; /* Mark as disconnected */
cleanup_client(client);
return;
} else {
snprintf(client->current_slide, BUFFER_SIZE, "Unknown command '%c'. Use SPACE, BACKSPACE, or Q.\n", command);
@ -97,22 +110,10 @@ void send_welcome_message(struct Client *client) {
const char *welcome_msg =
"Welcome to the git-slides presentation!\n"
"Use SPACE (forward), BACKSPACE (back), or Q (quit).\n\n";
write(client->fd, welcome_msg, strlen(welcome_msg));
write(client->fd, client->current_slide, strlen(client->current_slide));
write(client->fd, welcome_msg, strlen(welcome_msg));
}
/* Clean up client resources */
void cleanup_client(struct Client *client) {
if (client->fd != -1) {
close(client->fd);
client->fd = -1;
}
if (strlen(client->repo_path) > 0) {
char rm_command[CMD_SIZE];
snprintf(rm_command, sizeof(rm_command), "rm -rf %s", client->repo_path);
system(rm_command);
}
}
int main() {
int server_fd;
@ -151,13 +152,13 @@ int main() {
clients[i].fd = -1;
}
fds[0].fd = server_fd;
fds[0].events = POLLIN;
printf("Server running on port %d\n", PORT);
while (1) {
int num_fds = 1;
fds[0].fd = server_fd;
fds[0].events = POLLIN;
/* Prepare the pollfd array */
for (i = 0; i < MAX_CLIENTS; i++) {
@ -210,16 +211,17 @@ int main() {
load_slide_content(client->slides_path, client->current_slide);
send_telnet_negotiation(client_fd);
send_welcome_message(client);
printf("Client connected: %d\n", client_fd);
/* Discard any pending input */
fds[0].fd = client_fd;
fds[0].events = POLLIN;
while (poll(fds, 1, 20) > 0) {
while (poll(fds, 1, 500) > 0) {
char command;
read(client_fd, &command, 1);
}
printf("Go!\n");
send_welcome_message(client);
continue;
}
}