From 0e572589f39142d22c4b2c7235c1ca95cb9f441b Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Fri, 18 Feb 2022 20:24:23 +1100 Subject: [PATCH] Do not keep MappedFile fd opened According to the mmap man page this is not necessary, and this avoids exposing the fd. --- src/file.cc | 11 ++++------- src/file.hh | 1 - 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/file.cc b/src/file.cc index d80da197..a3a72ccc 100644 --- a/src/file.cc +++ b/src/file.cc @@ -208,7 +208,7 @@ String read_file(StringView filename, bool text) MappedFile::MappedFile(StringView filename) : data{nullptr} { - fd = open(filename.zstr(), O_RDONLY | O_NONBLOCK); + int fd = open(filename.zstr(), O_RDONLY | O_NONBLOCK); if (fd == -1) throw file_access_error(filename, strerror(errno)); @@ -222,16 +222,13 @@ MappedFile::MappedFile(StringView filename) data = (const char*)mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (data == MAP_FAILED) throw file_access_error{filename, strerror(errno)}; + close(fd); } MappedFile::~MappedFile() { - if (fd != -1) - { - if (data != nullptr) - munmap((void*)data, st.st_size); - close(fd); - } + if (data != nullptr) + munmap((void*)data, st.st_size); } MappedFile::operator StringView() const diff --git a/src/file.hh b/src/file.hh index b1dd0bcd..7f30c0b2 100644 --- a/src/file.hh +++ b/src/file.hh @@ -49,7 +49,6 @@ struct MappedFile operator StringView() const; - int fd; const char* data; struct stat st {}; };