Skip to content

Commit

Permalink
Close PolyGlot file descriptors after mmap
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasf committed Jan 7, 2023
1 parent d7c3edb commit 9cb8d3b
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions chess/polyglot.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,12 +337,13 @@ class MemoryMappedReader:
"""Maps a Polyglot opening book to memory."""

def __init__(self, filename: PathLike) -> None:
self.fd = os.open(filename, os.O_RDONLY | os.O_BINARY if hasattr(os, "O_BINARY") else os.O_RDONLY)

fd = os.open(filename, os.O_RDONLY | os.O_BINARY if hasattr(os, "O_BINARY") else os.O_RDONLY)
try:
self.mmap: Union[mmap.mmap, _EmptyMmap] = mmap.mmap(self.fd, 0, access=mmap.ACCESS_READ)
self.mmap: Union[mmap.mmap, _EmptyMmap] = mmap.mmap(fd, 0, access=mmap.ACCESS_READ)
except (ValueError, OSError):
self.mmap = _EmptyMmap() # Workaround for empty opening books.
finally:
os.close(fd)

if self.mmap.size() % ENTRY_STRUCT.size != 0:
raise IOError(f"invalid file size: ensure {filename!r} is a valid polyglot opening book")
Expand Down Expand Up @@ -514,11 +515,6 @@ def close(self) -> None:
"""Closes the reader."""
self.mmap.close()

try:
os.close(self.fd)
except OSError:
pass


def open_reader(path: PathLike) -> MemoryMappedReader:
"""
Expand Down

0 comments on commit 9cb8d3b

Please sign in to comment.