Ver Fonte

Open fd and socket with the CLOEXEC flag when available

Stéphane Raimbault há 13 anos atrás
pai
commit
b94ba026e0
2 ficheiros alterados com 13 adições e 2 exclusões
  1. 7 1
      src/modbus-rtu.c
  2. 6 1
      src/modbus-tcp.c

+ 7 - 1
src/modbus-rtu.c

@@ -373,6 +373,7 @@ static int _modbus_rtu_connect(modbus_t *ctx)
 #else
 #else
     struct termios tios;
     struct termios tios;
     speed_t speed;
     speed_t speed;
+    int flags;
 #endif
 #endif
     modbus_rtu_t *ctx_rtu = ctx->backend_data;
     modbus_rtu_t *ctx_rtu = ctx->backend_data;
 
 
@@ -526,7 +527,12 @@ static int _modbus_rtu_connect(modbus_t *ctx)
 
 
        Timeouts are ignored in canonical input mode or when the
        Timeouts are ignored in canonical input mode or when the
        NDELAY option is set on the file via open or fcntl */
        NDELAY option is set on the file via open or fcntl */
-    ctx->s = open(ctx_rtu->device, O_RDWR | O_NOCTTY | O_NDELAY | O_EXCL);
+    flags = O_RDWR | O_NOCTTY | O_NDELAY | O_EXCL;
+#ifdef O_CLOEXEC
+    flags |= O_CLOEXEC;
+#endif
+
+    ctx->s = open(ctx_rtu->device, flags);
     if (ctx->s == -1) {
     if (ctx->s == -1) {
         fprintf(stderr, "ERROR Can't open the device %s (%s)\n",
         fprintf(stderr, "ERROR Can't open the device %s (%s)\n",
                 ctx_rtu->device, strerror(errno));
                 ctx_rtu->device, strerror(errno));

+ 6 - 1
src/modbus-tcp.c

@@ -244,6 +244,7 @@ static int _modbus_tcp_connect(modbus_t *ctx)
     int rc;
     int rc;
     struct sockaddr_in addr;
     struct sockaddr_in addr;
     modbus_tcp_t *ctx_tcp = ctx->backend_data;
     modbus_tcp_t *ctx_tcp = ctx->backend_data;
+    int flags = SOCK_STREAM;
 
 
 #ifdef OS_WIN32
 #ifdef OS_WIN32
     if (_modbus_tcp_init_win32() == -1) {
     if (_modbus_tcp_init_win32() == -1) {
@@ -251,7 +252,11 @@ static int _modbus_tcp_connect(modbus_t *ctx)
     }
     }
 #endif
 #endif
 
 
-    ctx->s = socket(PF_INET, SOCK_STREAM, 0);
+#ifdef SOCK_CLOEXEC
+    flags |= SOCK_CLOEXEC;
+#endif
+
+    ctx->s = socket(PF_INET, flags, 0);
     if (ctx->s == -1) {
     if (ctx->s == -1) {
         return -1;
         return -1;
     }
     }