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.
This commit is contained in:
Willy Tarreau 2022-04-26 10:18:07 +02:00
parent b4f5fac886
commit a80e4a3546
2 changed files with 29 additions and 0 deletions

View 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.

View File

@ -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.