diff options
-rw-r--r-- | include/fileutils.h | 1 | ||||
-rw-r--r-- | lib/fileutils.c | 30 |
2 files changed, 31 insertions, 0 deletions
diff --git a/include/fileutils.h b/include/fileutils.h index 3353f69a0..e0e2ecee1 100644 --- a/include/fileutils.h +++ b/include/fileutils.h @@ -25,6 +25,7 @@ static inline FILE *xfmkstemp(char **tmpname, char *dir) return ret; } +extern int dup_fd_cloexec(int oldfd, int lowfd); extern int get_fd_tabsize(void); extern int mkdir_p(const char *path, mode_t mode); diff --git a/lib/fileutils.c b/lib/fileutils.c index bffa8ff34..81b38ad3a 100644 --- a/lib/fileutils.c +++ b/lib/fileutils.c @@ -50,6 +50,36 @@ int xmkstemp(char **tmpname, char *dir) return fd; } +int dup_fd_cloexec(int oldfd, int lowfd) +{ + int fd, flags, errno_save; + +#ifdef F_DUPFD_CLOEXEC + fd = fcntl(oldfd, F_DUPFD_CLOEXEC, lowfd); + if (fd >= 0) + return fd; +#endif + + fd = dup(oldfd); + if (fd < 0) + return fd; + + flags = fcntl(fd, F_GETFD); + if (flags < 0) + goto unwind; + if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) + goto unwind; + + return fd; + +unwind: + errno_save = errno; + close(fd); + errno = errno_save; + + return -1; +} + /* * portable getdtablesize() */ |