New submission from Christian Heimes <li...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue45915>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to