From a80e4a3546ccee7f8114a88a0a17e09e544d31e2 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Tue, 26 Apr 2022 10:18:07 +0200 Subject: [PATCH] MINOR: fd: add functions to set O_NONBLOCK and FD_CLOEXEC 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 | 8 ++++++++ src/fd.c | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/include/haproxy/fd.h b/include/haproxy/fd.h index 8bf30cd255..cf2d02b781 100644 --- a/include/haproxy/fd.h +++ b/include/haproxy/fd.h @@ -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. diff --git a/src/fd.c b/src/fd.c index c983b8c9aa..529cba739f 100644 --- 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. -- 2.39.5