]> git.ipfire.org Git - thirdparty/haproxy.git/commitdiff
MINOR: fd: add functions to set O_NONBLOCK and FD_CLOEXEC
authorWilly Tarreau <w@1wt.eu>
Tue, 26 Apr 2022 08:18:07 +0000 (10:18 +0200)
committerWilly Tarreau <w@1wt.eu>
Tue, 26 Apr 2022 08:59:48 +0000 (10:59 +0200)
Instead of seeing each location manipulate the fcntl() themselves and
often forget to check previous flags, let's centralize the functions to
do this. It also allows to drop fcntl.h from most call places and will
ease the adoption of different OS-specific mechanisms if needed. Note
that the fd_set_nonblock() function purposely doesn't check the previous
flags as it's meant to be used on new FDs only.

include/haproxy/fd.h
src/fd.c

index 8bf30cd255821b6d7f01abdf70525519890d031e..cf2d02b781f9a494c228a1d019611017a1790337 100644 (file)
@@ -59,6 +59,14 @@ extern volatile int ha_used_fds; // Number of FDs we're currently using
 void fd_delete(int fd);
 void _fd_delete_orphan(int fd);
 
+/* makes the new fd non-blocking and clears all other O_* flags;
+ * this is meant to be used on new FDs. Returns -1 on failure.
+ */
+int fd_set_nonblock(int fd);
+
+/* makes the fd close-on-exec; returns -1 on failure. */
+int fd_set_cloexec(int fd);
+
 /*
  * Take over a FD belonging to another thread.
  * Returns 0 on success, and -1 on failure.
index c983b8c9aa90e2da284d1c054886995ab1134a0c..529cba739fbc15e00fc879ad7bb4d9bc6083eedb 100644 (file)
--- a/src/fd.c
+++ b/src/fd.c
@@ -363,6 +363,27 @@ void fd_delete(int fd)
                _fd_delete_orphan(fd);
 }
 
+/* makes the new fd non-blocking and clears all other O_* flags;
+ * this is meant to be used on new FDs. Returns -1 on failure.
+ */
+int fd_set_nonblock(int fd)
+{
+       int ret = fcntl(fd, F_SETFL, O_NONBLOCK);
+
+       return ret;
+}
+
+/* sets the close-on-exec flag on fd; returns -1 on failure. */
+int fd_set_cloexec(int fd)
+{
+       int flags, ret;
+
+       flags = fcntl(fd, F_GETFD);
+       flags |= FD_CLOEXEC;
+       ret = fcntl(fd, F_SETFD, flags);
+       return ret;
+}
+
 /*
  * Take over a FD belonging to another thread.
  * unexpected_conn is the expected owner of the fd.