Stéphane Raimbault 12 жил өмнө
parent
commit
e6b648881e

+ 5 - 3
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
 }
 

+ 4 - 2
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)

+ 9 - 5
tests/bandwidth-server-one.c

@@ -1,5 +1,5 @@
 /*
- * Copyright © 2008-2012 Stéphane Raimbault <stephane.raimbault@gmail.com>
+ * Copyright © 2008-2013 Stéphane Raimbault <stephane.raimbault@gmail.com>
  *
  * 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;

+ 2 - 0
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;