From 1f74825313cb87e2c0ba9bfe5a8f1e55b1f5035d Mon Sep 17 00:00:00 2001 From: Ronald Oussoren Date: Thu, 7 Dec 2023 10:30:15 +0100 Subject: [PATCH] gh-109981: Fix support.fd_count() on macOS 14 (GH-112797) Use scanning "/dev/fd/" on macOS in support.fd_count(). That's both more efficient than scanning all possible file descriptors, and avoids crashing the interpreter when there are open "guarded" file descriptors. "Guarded" file descriptors are a macOS feature where file descriptors used by system libraries are marked and cause hard crashes when used by "user" code. (cherry picked from commit 953ee622b3901d3467e65e3484dcfa75ba6fcddf) Co-authored-by: Ronald Oussoren Co-authored-by: Victor Stinner --- Lib/test/support/os_helper.py | 11 +++++++++-- .../2023-12-06-12-11-13.gh-issue-109981.mOHg10.rst | 3 +++ 2 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/macOS/2023-12-06-12-11-13.gh-issue-109981.mOHg10.rst diff --git a/Lib/test/support/os_helper.py b/Lib/test/support/os_helper.py index f77cce89a37d57..8aa9549e577bb3 100644 --- a/Lib/test/support/os_helper.py +++ b/Lib/test/support/os_helper.py @@ -588,10 +588,17 @@ def fd_count(): """Count the number of open file descriptors. """ if sys.platform.startswith(('linux', 'freebsd', 'emscripten')): + fd_path = "/proc/self/fd" + elif sys.platform == "darwin": + fd_path = "/dev/fd" + else: + fd_path = None + + if fd_path is not None: try: - names = os.listdir("/proc/self/fd") + names = os.listdir(fd_path) # Subtract one because listdir() internally opens a file - # descriptor to list the content of the /proc/self/fd/ directory. + # descriptor to list the content of the directory. return len(names) - 1 except FileNotFoundError: pass diff --git a/Misc/NEWS.d/next/macOS/2023-12-06-12-11-13.gh-issue-109981.mOHg10.rst b/Misc/NEWS.d/next/macOS/2023-12-06-12-11-13.gh-issue-109981.mOHg10.rst new file mode 100644 index 00000000000000..f86ab2c37ee6ec --- /dev/null +++ b/Misc/NEWS.d/next/macOS/2023-12-06-12-11-13.gh-issue-109981.mOHg10.rst @@ -0,0 +1,3 @@ +Use ``/dev/fd`` on macOS to determine the number of open files in +``test.support.os_helper.fd_count`` to avoid a crash with "guarded" file +descriptors when probing for open files.