diff --git a/src/modbus-rtu.c b/src/modbus-rtu.c index 276c344..b642dfc 100644 --- a/src/modbus-rtu.c +++ b/src/modbus-rtu.c @@ -373,6 +373,7 @@ static int _modbus_rtu_connect(modbus_t *ctx) #else struct termios tios; speed_t speed; + int flags; #endif 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 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) { fprintf(stderr, "ERROR Can't open the device %s (%s)\n", ctx_rtu->device, strerror(errno)); diff --git a/src/modbus-tcp.c b/src/modbus-tcp.c index f589c05..b215b18 100644 --- a/src/modbus-tcp.c +++ b/src/modbus-tcp.c @@ -244,6 +244,7 @@ static int _modbus_tcp_connect(modbus_t *ctx) int rc; struct sockaddr_in addr; modbus_tcp_t *ctx_tcp = ctx->backend_data; + int flags = SOCK_STREAM; #ifdef OS_WIN32 if (_modbus_tcp_init_win32() == -1) { @@ -251,7 +252,11 @@ static int _modbus_tcp_connect(modbus_t *ctx) } #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) { return -1; }