[New-bugs-announce] [issue45915] Use fcntl(fd, F_GETFD) to check whether an fd is valid

Christian Heimes report at bugs.python.org
Sun Nov 28 05:13:06 EST 2021


New submission from Christian Heimes <lists at cheimes.de>:

is_valid_fd() uses dup() or fstat() to check whether an fd is valid. Both operations are costly. 

fcntl() with F_GETFD returns the file descriptor flags (e.g. CLOEXEC) and -1 with errno set to EBADF when fd is not an open file descriptor. It's faster than duplicating + closing a fd or calling fstat(). The idea to use fcntl(fd, F_GETFD) is inspired by the patch [1]. According to Stackoverflow [2]:

> fcntl(fd, F_GETFD) is the canonical cheapest way to check that fd is a valid open file descriptor.
> F_GETFD is cheaper in principle since it only dereferences the (process-local) file descriptor in kernel space, not the underlying open file description (process-shared) which it refers to.

[1] https://github.com/singlestore-labs/cpython/commit/0364554615c79b9364a0acf3038147a999ea2219

[2] https://stackoverflow.com/questions/12340695/how-to-check-if-a-given-file-descriptor-stored-in-a-variable-is-still-valid

----------
components: C API
messages: 407197
nosy: christian.heimes, vstinner
priority: normal
severity: normal
status: open
title: Use fcntl(fd, F_GETFD) to check whether an fd is valid
type: behavior
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45915>
_______________________________________


More information about the New-bugs-announce mailing list