From b94ba026e0e61aac48f2fe244113640df90cb211 Mon Sep 17 00:00:00 2001 From: Stéphane Raimbault Date: Wed, 2 Nov 2011 23:15:39 +0100 Subject: [PATCH] Open fd and socket with the CLOEXEC flag when available --- src/modbus-rtu.c | 8 +++++++- src/modbus-tcp.c | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) 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; } -- libgit2 0.21.4