From 37a7a58a3154bfbf1cb8cff7562eaa627dacf61f Mon Sep 17 00:00:00 2001 From: Kris Burney <burneykb@iastate.edu> Date: Thu, 27 Oct 2016 12:36:00 -0500 Subject: [PATCH] added safe_close_fd function --- groundStation/src/microcart_cli.c | 32 ++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/groundStation/src/microcart_cli.c b/groundStation/src/microcart_cli.c index 76e59968a..4b1a66c47 100644 --- a/groundStation/src/microcart_cli.c +++ b/groundStation/src/microcart_cli.c @@ -43,6 +43,7 @@ void performCommand(char *, char *); int startsWith(const char *, const char *); int safe_fd_set(int , fd_set* , int* ); int safe_fd_clr(int , fd_set* , int* ); +static void safe_close_fd(int fd, pthread_mutex_t *mutexLock); static void cb(struct ucart_vrpn_TrackerData *); static int new_client(int fd); @@ -51,7 +52,7 @@ static ssize_t get_client_index(int fd); /* Returns pointer to client buffer, or -1 */ static char * get_client_buffer(int fd); /* Returns -1 on error */ -static int remove_client(fd); +static int remove_client(int fd); /* Thread-safe wrappers */ pthread_mutex_t quadSocketMutex; @@ -252,9 +253,8 @@ int main(int argc, char **argv) for(int i = 0; i < MAX_CLIENTS; ++i) { if(client_fds[i] != -1) { char buff; - if(recv(client_fds[i],&buff, 1, MSG_PEEK | MSG_DONTWAIT) < 0) { + if(recv(client_fds[i],&buff, 1, MSG_PEEK | MSG_DONTWAIT) < 0) remove_client(client_fds[i]); - } } } } @@ -262,13 +262,9 @@ int main(int argc, char **argv) // ucart_vrpn_tracker_freeInstance(tracker); - if (pthread_mutex_lock(&quadSocketMutex)) { - err(-2, "pthrtead_mutex_lock (%s:%d):", __FILE__, __LINE__); - } - close(zyboSocket); - if (pthread_mutex_unlock(&quadSocketMutex)) { - err(-2, "pthrtead_mutex_unlock (%s:%d):", __FILE__, __LINE__); - } + safe_close_fd(zyboSocket, &quadSocketMutex); + + closeLogFile(); return 0; @@ -479,14 +475,24 @@ static char * get_client_buffer(int fd) } } -static int remove_client(fd) { +static int remove_client(int fd) { ssize_t slot = get_client_index(fd); if(slot == -1) - return slot; + return -1; char *clientBuffer = get_client_buffer(fd); if(clientBuffer == NULL) return -1; clientBuffer = '\0'; - client_fds[clientIndex] = -1; + client_fds[slot] = -1; return 0; +} + +static void safe_close_fd(int fd, pthread_mutex_t *mutexLock) { + if (pthread_mutex_lock(mutexLock)) { + err(-2, "pthrtead_mutex_lock (%s:%d):", __FILE__, __LINE__); + } + close(fd); + if (pthread_mutex_unlock(mutexLock)) { + err(-2, "pthrtead_mutex_unlock (%s:%d):", __FILE__, __LINE__); + } } \ No newline at end of file -- GitLab