Commit 367f5d37 authored by Victor Stinner's avatar Victor Stinner

Issue #21058: Fix a leak of file descriptor in tempfile.NamedTemporaryFile(),

close the file descriptor if os.fdopen() fails
parent 74a4ebae
......@@ -460,8 +460,12 @@ def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
flags |= _os.O_TEMPORARY
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
file = _os.fdopen(fd, mode, bufsize)
return _TemporaryFileWrapper(file, name, delete)
try:
file = _os.fdopen(fd, mode, bufsize)
return _TemporaryFileWrapper(file, name, delete)
except Exception:
_os.close(fd)
raise
if _os.name != 'posix' or _os.sys.platform == 'cygwin':
# On non-POSIX and Cygwin systems, assume that we cannot unlink a file
......
......@@ -771,6 +771,24 @@ class test_NamedTemporaryFile(TC):
pass
self.assertRaises(ValueError, use_closed)
def test_no_leak_fd(self):
# Issue #21058: don't leak file descriptor when fdopen() fails
old_close = os.close
old_fdopen = os.fdopen
closed = []
def close(fd):
closed.append(fd)
def fdopen(*args):
raise ValueError()
os.close = close
os.fdopen = fdopen
try:
self.assertRaises(ValueError, tempfile.NamedTemporaryFile)
self.assertEqual(len(closed), 1)
finally:
os.close = old_close
os.fdopen = old_fdopen
# How to test the mode and bufsize parameters?
test_classes.append(test_NamedTemporaryFile)
......
......@@ -40,6 +40,9 @@ Core and Builtins
Library
-------
- Issue #21058: Fix a leak of file descriptor in tempfile.NamedTemporaryFile(),
close the file descriptor if os.fdopen() fails
- Issue #20283: RE pattern methods now accept the string keyword parameters
as documented. The pattern and source keyword parameters are left as
deprecated aliases.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment