From 6fcc657d7a2fc737c571ac35ea8ad1b26bf44957 Mon Sep 17 00:00:00 2001 From: Lucas Zadrozny Date: Tue, 20 Aug 2024 20:53:32 +1000 Subject: [PATCH] Fix race condition surrounding DB reopening during fork --- src/iso19111/factory.cpp | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/iso19111/factory.cpp b/src/iso19111/factory.cpp index bd4acf2b65..a0332d3ae9 100644 --- a/src/iso19111/factory.cpp +++ b/src/iso19111/factory.cpp @@ -627,8 +627,23 @@ SQLiteHandleCache::getHandle(const std::string &path, PJ_CONTEXT *ctx) { #ifdef REOPEN_SQLITE_DB_AFTER_FORK if (firstTime_) { firstTime_ = false; - pthread_atfork(nullptr, nullptr, - []() { SQLiteHandleCache::get().invalidateHandles(); }); + pthread_atfork( + []() { + // This mutex needs to be acquired by 'invalidateHandles()'. + // The forking thread needs to own this mutex during the fork. + // Otherwise there's an opporunity for another thread to own + // the mutex during the fork, leaving the child process unable + // to acquire the mutex in invalidateHandles(). + SQLiteHandleCache::get().sMutex_.lock(); + }, + []() { + SQLiteHandleCache::get().sMutex_.unlock(); + }, + []() { + SQLiteHandleCache::get().sMutex_.unlock(); + SQLiteHandleCache::get().invalidateHandles(); + } + ); } #endif