diff --git a/Abstracts/ReloadWorkers.php b/Abstracts/ReloadWorkers.php index 09e46f6..b56b58a 100644 --- a/Abstracts/ReloadWorkers.php +++ b/Abstracts/ReloadWorkers.php @@ -7,6 +7,8 @@ use Swoole\Process; trait ReloadWorkers { + private static ?int $cachedMasterPid = null; + /** * @return void */ @@ -22,6 +24,11 @@ trait ReloadWorkers private function getMasterPid(): ?int { + if (self::$cachedMasterPid !== null && $this->isCachedMasterPid(self::$cachedMasterPid)) { + return self::$cachedMasterPid; + } + + self::$cachedMasterPid = null; $processes = $this->listProcesses(); $candidates = []; @@ -41,6 +48,7 @@ trait ReloadWorkers |> array_unique(...) |> array_values(...) as $pid) { if ($this->isProcessAlive($pid) && $this->isMasterPid($pid, $processes)) { + self::$cachedMasterPid = $pid; return $pid; } } @@ -48,6 +56,26 @@ trait ReloadWorkers return null; } + private function isCachedMasterPid(int $pid): bool + { + if (!$this->isProcessAlive($pid)) { + return false; + } + + $command = $this->readProcessCommand($pid); + return $command !== '' && $this->isMasterProcessCommand($command) && $this->isSameAppProcess($pid); + } + + private function readProcessCommand(int $pid): string + { + $cmdline = @file_get_contents('/proc/' . $pid . '/cmdline'); + if (is_string($cmdline) && $cmdline !== '') { + return trim(str_replace("\0", ' ', $cmdline)); + } + + return ''; + } + private function isMasterPid(int $pid, array $processes): bool { foreach ($processes as $process) {