From 38038f6a48bc7e03ae1490d185a14cbdb2a58dd8 Mon Sep 17 00:00:00 2001 From: Per Noergaard Christensen Date: Mon, 12 Sep 2016 23:08:51 +0200 Subject: [PATCH] lib: use O_CLOEXEC flag when opening EtherCAT master device This flag specifies that the file descriptor should be closed when an exec function is invoked. When a file descriptor is allocated (as with open or dup), O_CLOEXEC bit is initially cleared on the new file descriptor, meaning that descriptor will survive into the new program after exec. Setting O_CLOEXEC avoid this survival of the desciptor in the new program. And setting it at open() time is the only race-free way to avoid accidentally leaking the fd via other threads that concurrently do fork()+exec() (or similar, e.g. posix_spawn). --- lib/common.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common.c b/lib/common.c index 88bcabe5..86a38586 100644 --- a/lib/common.c +++ b/lib/common.c @@ -97,9 +97,9 @@ ec_master_t *ecrt_open_master(unsigned int master_index) master_index); #ifdef USE_RTDM - master->fd = rt_dev_open(path, O_RDWR); + master->fd = rt_dev_open(path, O_RDWR | O_CLOEXEC); #else - master->fd = open(path, O_RDWR); + master->fd = open(path, O_RDWR | O_CLOEXEC); #endif if (EC_IOCTL_IS_ERROR(master->fd)) { EC_PRINT_ERR("Failed to open %s: %s\n", path,