Commit e6b648881e5017fda3b02edf3bd9ce219aa8910e

Authored by Stéphane Raimbault
1 parent 32062c78

Safer modbus_close

src/modbus-rtu.c
... ... @@ -925,7 +925,7 @@ int modbus_rtu_get_rts(modbus_t *ctx) {
925 925  
926 926 static void _modbus_rtu_close(modbus_t *ctx)
927 927 {
928   - /* Closes the file descriptor in RTU mode */
  928 + /* Restore line settings and close file descriptor in RTU mode */
929 929 modbus_rtu_t *ctx_rtu = ctx->backend_data;
930 930  
931 931 #if defined(_WIN32)
... ... @@ -938,8 +938,10 @@ static void _modbus_rtu_close(modbus_t *ctx)
938 938 fprintf(stderr, "ERROR Error while closing handle (LastError %d)\n",
939 939 (int)GetLastError());
940 940 #else
941   - tcsetattr(ctx->s, TCSANOW, &(ctx_rtu->old_tios));
942   - close(ctx->s);
  941 + if (ctx->s != -1) {
  942 + tcsetattr(ctx->s, TCSANOW, &(ctx_rtu->old_tios));
  943 + close(ctx->s);
  944 + }
943 945 #endif
944 946 }
945 947  
... ...
src/modbus-tcp.c
... ... @@ -418,8 +418,10 @@ static int _modbus_tcp_pi_connect(modbus_t *ctx)
418 418 /* Closes the network connection and socket in TCP mode */
419 419 static void _modbus_tcp_close(modbus_t *ctx)
420 420 {
421   - shutdown(ctx->s, SHUT_RDWR);
422   - close(ctx->s);
  421 + if (ctx->s != -1) {
  422 + shutdown(ctx->s, SHUT_RDWR);
  423 + close(ctx->s);
  424 + }
423 425 }
424 426  
425 427 static int _modbus_tcp_flush(modbus_t *ctx)
... ...
tests/bandwidth-server-one.c
1 1 /*
2   - * Copyright © 2008-2012 Stéphane Raimbault <stephane.raimbault@gmail.com>
  2 + * Copyright © 2008-2013 Stéphane Raimbault <stephane.raimbault@gmail.com>
3 3 *
4 4 * This program is free software: you can redistribute it and/or modify
5 5 * it under the terms of the GNU General Public License as published by
... ... @@ -36,9 +36,9 @@ enum {
36 36  
37 37 int main(int argc, char *argv[])
38 38 {
39   - int socket;
40   - modbus_t *ctx;
41   - modbus_mapping_t *mb_mapping;
  39 + int socket = -1;
  40 + modbus_t *ctx = NULL;
  41 + modbus_mapping_t *mb_mapping = NULL;
42 42 int rc;
43 43 int use_backend;
44 44  
... ... @@ -92,7 +92,11 @@ int main(int argc, char *argv[])
92 92 printf("Quit the loop: %s\n", modbus_strerror(errno));
93 93  
94 94 modbus_mapping_free(mb_mapping);
95   - close(socket);
  95 + if (socket != -1) {
  96 + close(socket);
  97 + }
  98 + /* For RTU, skipped by TCP (no TCP connect) */
  99 + modbus_close(ctx);
96 100 modbus_free(ctx);
97 101  
98 102 return 0;
... ...
tests/unit-test-server.c
... ... @@ -191,6 +191,8 @@ int main(int argc, char*argv[])
191 191 }
192 192 modbus_mapping_free(mb_mapping);
193 193 free(query);
  194 + /* For RTU */
  195 + modbus_close(ctx);
194 196 modbus_free(ctx);
195 197  
196 198 return 0;
... ...