From d80cc79e8f0991b9e0a0ce2d0cf47408c6e57d46 Mon Sep 17 00:00:00 2001 From: "flyingscorpio@clevo" Date: Mon, 24 Oct 2022 23:15:34 +0200 Subject: [PATCH] Add disconnect_client function --- src/server.c | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/src/server.c b/src/server.c index 2053470..060fc45 100644 --- a/src/server.c +++ b/src/server.c @@ -108,11 +108,8 @@ int main(int argc, char *argv[]) { close(client_sockid); continue; } - clients[client_id].id = client_id; - clients[client_id].sockid = client_sockid; - clients[client_id].pipe[0] = message_pipe[0]; - clients[client_id].pipe[1] = message_pipe[1]; + /* Start client threads */ if (pthread_create(&clientsender, NULL, ClientSender, &clients[client_id]) != 0) { fprintf(stderr, "pthread_create: error for ClientSender\n"); exit(EXIT_FAILURE); @@ -122,12 +119,13 @@ int main(int argc, char *argv[]) { exit(EXIT_FAILURE); } + /* Register client */ + clients[client_id].id = client_id; + clients[client_id].sockid = client_sockid; + clients[client_id].pipe[0] = message_pipe[0]; + clients[client_id].pipe[1] = message_pipe[1]; clients[client_id].listener_thread = clientlistener; clients[client_id].sender_thread = clientsender; - - // TODO: joining here prevents creating other clients, need to move the joins to some client_disconnect function - (void) pthread_join(clientsender, &retval); - (void) pthread_join(clientlistener, &retval); } } @@ -175,6 +173,33 @@ int get_next_free_client_id(void) { return -1; // Error: reached end of array } +int disconnect_client(int client_id) { + void *retval; + + if ((clients[client_id].id == -1) || + (clients[client_id].sockid == -1) || + (clients[client_id].pipe[0] == -1) || + (clients[client_id].pipe[1] == -1)) { + fprintf(stderr, "disconnect_client: couldn't find client #%d, already disconnected?\n", client_id); + return -1; + } + + clients[client_id].id = -1; + close(clients[client_id].sockid); + clients[client_id].sockid = -1; + close(clients[client_id].pipe[0]); + clients[client_id].pipe[0] = -1; + close(clients[client_id].pipe[1]); + clients[client_id].pipe[1] = -1; + + (void) pthread_join(clients[client_id].sender_thread, &retval); + clients[client_id].sender_thread = -1; + (void) pthread_join(clients[client_id].listener_thread, &retval); + clients[client_id].listener_thread = -1; + + return 0; +} + /* Thread, parses and handles messages */ void *Dispatcher(void *arg) { pthread_exit(0);