loop: don't leak dir_fd for LoopControl

If `dir_fd` is not passed into the constructor of LoopControl,
"/dev" will be opened, but it was not closed and thus would
leak the fd.
This commit is contained in:
Christian Kellner 2021-08-08 15:25:30 +00:00 committed by Tom Gundersen
parent 73f24c68a2
commit 62082733e9

View file

@ -317,9 +317,12 @@ class LoopControl:
or None to use /dev (default is None)
"""
if not dir_fd:
dir_fd = os.open("/dev", os.O_DIRECTORY)
self.fd = os.open("loop-control", os.O_RDWR, dir_fd=dir_fd)
with contextlib.ExitStack() as stack:
if not dir_fd:
dir_fd = os.open("/dev", os.O_DIRECTORY)
stack.callback(lambda: os.close(dir_fd))
self.fd = os.open("loop-control", os.O_RDWR, dir_fd=dir_fd)
def __del__(self):
self.close()