From e6b648881e5017fda3b02edf3bd9ce219aa8910e Mon Sep 17 00:00:00 2001 From: Stéphane Raimbault Date: Wed, 1 May 2013 15:54:07 +0200 Subject: [PATCH] Safer modbus_close --- src/modbus-rtu.c | 8 +++++--- src/modbus-tcp.c | 6 ++++-- tests/bandwidth-server-one.c | 14 +++++++++----- tests/unit-test-server.c | 2 ++ 4 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/modbus-rtu.c b/src/modbus-rtu.c index 917221d..858685f 100644 --- a/src/modbus-rtu.c +++ b/src/modbus-rtu.c @@ -925,7 +925,7 @@ int modbus_rtu_get_rts(modbus_t *ctx) { static void _modbus_rtu_close(modbus_t *ctx) { - /* Closes the file descriptor in RTU mode */ + /* Restore line settings and close file descriptor in RTU mode */ modbus_rtu_t *ctx_rtu = ctx->backend_data; #if defined(_WIN32) @@ -938,8 +938,10 @@ static void _modbus_rtu_close(modbus_t *ctx) fprintf(stderr, "ERROR Error while closing handle (LastError %d)\n", (int)GetLastError()); #else - tcsetattr(ctx->s, TCSANOW, &(ctx_rtu->old_tios)); - close(ctx->s); + if (ctx->s != -1) { + tcsetattr(ctx->s, TCSANOW, &(ctx_rtu->old_tios)); + close(ctx->s); + } #endif } diff --git a/src/modbus-tcp.c b/src/modbus-tcp.c index 261a605..ef8ea4b 100644 --- a/src/modbus-tcp.c +++ b/src/modbus-tcp.c @@ -418,8 +418,10 @@ static int _modbus_tcp_pi_connect(modbus_t *ctx) /* Closes the network connection and socket in TCP mode */ static void _modbus_tcp_close(modbus_t *ctx) { - shutdown(ctx->s, SHUT_RDWR); - close(ctx->s); + if (ctx->s != -1) { + shutdown(ctx->s, SHUT_RDWR); + close(ctx->s); + } } static int _modbus_tcp_flush(modbus_t *ctx) diff --git a/tests/bandwidth-server-one.c b/tests/bandwidth-server-one.c index 7a02751..9627f2a 100644 --- a/tests/bandwidth-server-one.c +++ b/tests/bandwidth-server-one.c @@ -1,5 +1,5 @@ /* - * Copyright © 2008-2012 Stéphane Raimbault + * Copyright © 2008-2013 Stéphane Raimbault * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -36,9 +36,9 @@ enum { int main(int argc, char *argv[]) { - int socket; - modbus_t *ctx; - modbus_mapping_t *mb_mapping; + int socket = -1; + modbus_t *ctx = NULL; + modbus_mapping_t *mb_mapping = NULL; int rc; int use_backend; @@ -92,7 +92,11 @@ int main(int argc, char *argv[]) printf("Quit the loop: %s\n", modbus_strerror(errno)); modbus_mapping_free(mb_mapping); - close(socket); + if (socket != -1) { + close(socket); + } + /* For RTU, skipped by TCP (no TCP connect) */ + modbus_close(ctx); modbus_free(ctx); return 0; diff --git a/tests/unit-test-server.c b/tests/unit-test-server.c index ebf47e1..f60d16c 100644 --- a/tests/unit-test-server.c +++ b/tests/unit-test-server.c @@ -191,6 +191,8 @@ int main(int argc, char*argv[]) } modbus_mapping_free(mb_mapping); free(query); + /* For RTU */ + modbus_close(ctx); modbus_free(ctx); return 0; -- libgit2 0.21.4