Skip to content

Commit d4a146d

Browse files
[3.12] GH-89727: Fix FD leak on os.fwalk() generator finalization. (GH-119766) (#119768)
GH-89727: Fix FD leak on `os.fwalk()` generator finalization. (GH-119766) Follow-up to 3c890b5. Ensure we `os.close()` open file descriptors when the `os.fwalk()` generator is finalized. (cherry picked from commit a5fef80) Co-authored-by: Barney Gale <barney.gale@gmail.com>
1 parent aae371b commit d4a146d

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

Lib/os.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -478,8 +478,15 @@ def fwalk(top=".", topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=
478478
top = fspath(top)
479479
stack = [(_fwalk_walk, (True, dir_fd, top, top, None))]
480480
isbytes = isinstance(top, bytes)
481-
while stack:
482-
yield from _fwalk(stack, isbytes, topdown, onerror, follow_symlinks)
481+
try:
482+
while stack:
483+
yield from _fwalk(stack, isbytes, topdown, onerror, follow_symlinks)
484+
finally:
485+
# Close any file descriptors still on the stack.
486+
while stack:
487+
action, value = stack.pop()
488+
if action == _fwalk_close:
489+
close(value)
483490

484491
# Each item in the _fwalk() stack is a pair (action, args).
485492
_fwalk_walk = 0 # args: (isroot, dirfd, toppath, topname, entry)

Lib/test/test_os.py

+21
Original file line numberDiff line numberDiff line change
@@ -1671,6 +1671,27 @@ def test_fd_leak(self):
16711671
self.addCleanup(os.close, newfd)
16721672
self.assertEqual(newfd, minfd)
16731673

1674+
@unittest.skipIf(
1675+
support.is_emscripten, "Cannot dup stdout on Emscripten"
1676+
)
1677+
@unittest.skipIf(
1678+
support.is_android, "dup return value is unpredictable on Android"
1679+
)
1680+
def test_fd_finalization(self):
1681+
# Check that close()ing the fwalk() generator closes FDs
1682+
def getfd():
1683+
fd = os.dup(1)
1684+
os.close(fd)
1685+
return fd
1686+
for topdown in (False, True):
1687+
old_fd = getfd()
1688+
it = self.fwalk(os_helper.TESTFN, topdown=topdown)
1689+
self.assertEqual(getfd(), old_fd)
1690+
next(it)
1691+
self.assertGreater(getfd(), old_fd)
1692+
it.close()
1693+
self.assertEqual(getfd(), old_fd)
1694+
16741695
# fwalk() keeps file descriptors open
16751696
test_walk_many_open_files = None
16761697

0 commit comments

Comments
 (0)