summaryrefslogtreecommitdiffstats
path: root/lib/fileutils.c
diff options
context:
space:
mode:
authorGuillem Jover2015-06-06 06:19:05 +0200
committerKarel Zak2015-06-08 12:10:02 +0200
commit8e86d93d1e3f0c11b3fdca3246c4f3a267acf8eb (patch)
tree50db242d8bde7b5c63807a6bac6a3b36360d9be3 /lib/fileutils.c
parentman: fix nolazytime typo in mount(8) (diff)
downloadkernel-qcow2-util-linux-8e86d93d1e3f0c11b3fdca3246c4f3a267acf8eb.tar.gz
kernel-qcow2-util-linux-8e86d93d1e3f0c11b3fdca3246c4f3a267acf8eb.tar.xz
kernel-qcow2-util-linux-8e86d93d1e3f0c11b3fdca3246c4f3a267acf8eb.zip
lib/fileutils: Add new dup_fd_cloexec function
This function duplicates and marks a file descriptor as close-on-exec. Takes care of build and run-time support for the fcntl F_DUPFD_CLOEXEC command, and other errors. Signed-off-by: Guillem Jover <guillem@hadrons.org>
Diffstat (limited to 'lib/fileutils.c')
-rw-r--r--lib/fileutils.c30
1 files changed, 30 insertions, 0 deletions
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()
*/