From b4c44c4998a397b307179a3bf27dcf4c0f9729a5 Mon Sep 17 00:00:00 2001 From: Adrien Date: Mon, 24 Feb 2025 14:32:24 +0100 Subject: [PATCH] Handle shared locks when reading the file to avoid race conditions --- src/IniReader.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/IniReader.php b/src/IniReader.php index 56c3d7f..aad70b9 100644 --- a/src/IniReader.php +++ b/src/IniReader.php @@ -341,6 +341,20 @@ private function getFileContent($filename) if (!$handle) { return false; } + + // Ensuring we have a shared lock to avoid race conditions when another process is writing to the file. + $flockRetries = 0; + while (true) { + if (flock($handle, LOCK_SH)) { + break; + } + if ($flockRetries >= 20) { + throw new Exception("Timeout after trying to get a shared lock on file $filename."); + } + usleep(100 * 1000); + $flockRetries++; + } + $ini = fread($handle, filesize($filename)); fclose($handle); return $ini;