8000 bpo-45915: use fcntl(fd, F_GETFD) in is_valid_fd() (GH-29821) · python/cpython@f87ea03 · GitHub
[go: up one dir, main page]

Skip to content

Commit f87ea03

Browse files
authored
bpo-45915: use fcntl(fd, F_GETFD) in is_valid_fd() (GH-29821)
1 parent aaf4222 commit f87ea03

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``is_valid_fd`` now uses faster ``fcntl(fd, F_GETFD)`` on Linux, macOS, and Windows.

Python/pylifecycle.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
# include <langinfo.h> // nl_langinfo(CODESET)
3131
#endif
3232

33+
#ifdef HAVE_FCNTL_H
34+
# include <fcntl.h> // F_GETFD
35+
#endif
36+
3337
#ifdef MS_WINDOWS
3438
# undef BYTE
3539
# include "windows.h"
@@ -2129,18 +2133,26 @@ is_valid_fd(int fd)
21292133
startup. Problem: dup() doesn't check if the file descriptor is valid on
21302134
some platforms.
21312135
2136+
fcntl(fd, F_GETFD) is even faster, because it only checks the process table.
2137+
21322138
bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
21332139
side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
21342140
EBADF. FreeBSD has similar issue (bpo-32849).
21352141
21362142
Only use dup() on platforms where dup() is enough to detect invalid FD in
2137-
corner cases: on Linux and Windows (bpo-32849). */
2138-
#if defined(__linux__) || defined(MS_WINDOWS)
2143+
corner cases: on Linux and Windows (bpo-32849).
2144+
*/
21392145
if (fd < 0) {
21402146
return 0;
21412147
}
2148+
#if defined(F_GETFD) && (defined(__linux__) || defined(__APPLE__) || defined(MS_WINDOWS))
2149+
int res;
2150+
_Py_BEGIN_SUPPRESS_IPH
2151+
res = fcntl(fd, F_GETFD);
2152+
_Py_END_SUPPRESS_IPH
2153+
return res >= 0;
2154+
#elif defined(__linux__) || defined(MS_WINDOWS)
21422155
int fd2;
2143-
21442156
_Py_BEGIN_SUPPRESS_IPH
21452157
fd2 = dup(fd);
21462158
if (fd2 >= 0) {

0 commit comments

Comments
 (0)
0