summaryrefslogtreecommitdiff
path: root/lib/fd-safer.c
diff options
context:
space:
mode:
authorEric Blake <ebb9@byu.net>2009-12-05 06:36:33 -0700
committerEric Blake <ebb9@byu.net>2009-12-05 14:36:40 -0700
commit14449a1dacca44c4f933d5fc207c7fa56e6c0fb7 (patch)
tree5f6cc0aebae6f1df589d9ae5d64f7608d7a24eb2 /lib/fd-safer.c
parent173359dbe40ac4381088060b0f26e66529fa0f29 (diff)
downloadgnulib-14449a1dacca44c4f933d5fc207c7fa56e6c0fb7.tar.gz
unistd-safer: allow preservation of cloexec status via flag
If cloexec is in use, allow the ability to preserve cloexec flag across *_safer functions. * lib/unistd-safer.h (dup_safer_flag, fd_safer_flag): New prototypes. * lib/dup-safer.c (dup_safer_flag): New function. * lib/fd-safer.c (fd_safer_flag): Likewise. * modules/cloexec (configure.ac): Set witness. Signed-off-by: Eric Blake <ebb9@byu.net>
Diffstat (limited to 'lib/fd-safer.c')
-rw-r--r--lib/fd-safer.c29
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/fd-safer.c b/lib/fd-safer.c
index fb9900180e..d2e1309c84 100644
--- a/lib/fd-safer.c
+++ b/lib/fd-safer.c
@@ -48,3 +48,32 @@ fd_safer (int fd)
return fd;
}
+
+#if GNULIB_CLOEXEC
+
+/* Return FD, unless FD would be a copy of standard input, output, or
+ error; in that case, return a duplicate of FD, closing FD. If FLAG
+ contains O_CLOEXEC, the returned FD will have close-on-exec
+ semantics. On failure to duplicate, close FD, set errno, and
+ return -1. Preserve errno if FD is negative, so that the caller
+ can always inspect errno when the returned value is negative.
+
+ This function is usefully wrapped around functions that return file
+ descriptors, e.g., fd_safer_flag (open ("file", O_RDONLY | flag), flag). */
+
+int
+fd_safer_flag (int fd, int flag)
+{
+ if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
+ {
+ int f = dup_safer_flag (fd, flag);
+ int e = errno;
+ close (fd);
+ errno = e;
+ fd = f;
+ }
+
+ return fd;
+}
+
+#endif /* GNULIB_CLOEXEC */