定時任務、手動觸發、多伺服器部署等場景下,同一 PHP 腳本可能被並發執行。基於 flock() 文件鎖 + ps 進程驗證的 SyncProcess 類,實現高併發安全的單實例執行保護,支援進程異常中斷自動恢復。
<?php
/**
* 同一個 PHP 進程只運行一次
* 基於文件鎖 + PID 存活驗證,Linux 專用,高併發安全
*/
class SyncProcess {
private string $pidFile;
public function __construct(string $pidFile) {
$this->pidFile = $pidFile;
}
/**
* 非阻塞檢查:是否有相同任務正在運行
* @return bool true=正在運行(應退出), false=可繼續執行
*/
public function check(): bool {
if (PHP_OS !== 'Linux') {
trigger_error(__CLASS__ . ' can only run in Linux', E_USER_WARNING);
return true; // 非 Linux 環境保守返回 true 防止並發
}
if (empty($this->pidFile)) {
trigger_error('pid file cannot be empty', E_USER_WARNING);
return true;
}
$pidDir = dirname($this->pidFile);
if (!is_dir($pidDir)) {
trigger_error("pid file dir ($pidFile) is invalid", E_USER_WARNING);
return true;
}
// 確保 PID 檔存在(首次運行時建立空檔)
clearstatcache(true, $this->pidFile);
if (!file_exists($this->pidFile)) {
file_put_contents($this->pidFile, '', LOCK_EX);
}
$fp = fopen($this->pidFile, 'r+');
if (!$fp) {
trigger_error("Cannot open pid file: {$this->pidFile}", E_USER_WARNING);
return true;
}
// 非阻塞排他鎖:獲取失敗 = 有其他進程持有鎖 = 正在運行
if (!flock($fp, LOCK_EX | LOCK_NB)) {
fclose($fp);
return true;
}
// 讀取檔案中記錄的 PID
$pid = trim(fgets($fp));
// 驗證該 PID 進程是否真實存在
$running = $this->isProcessRunning($pid);
if (!$running) {
// 進程已死,奪佔鎖並寫入自身 PID
fseek($fp, 0);
ftruncate($fp, 0);
fwrite($fp, (string)getmypid());
}
flock($fp, LOCK_UN);
fclose($fp);
return $running;
}
/**
* 驗證 PID 進程是否存活
*/
private function isProcessRunning(string $pid): bool {
if (!is_numeric($pid) || $pid <= 0) {
return false;
}
// ps -o pid --no-headers -p PID : 只輸出 PID 欄位,無標題
$output = [];
$line = exec("ps -o pid --no-headers -p $pid", $output);
$line = trim($line);
// 精確匹配 PID(避免部分匹配)
if ($line === $pid) {
return true;
}
// 異常情況:exec 返回非預期輸出
if (!empty($output)) {
$msg = implode(PHP_EOL, $output);
trigger_error("Unexpected ps output for PID $pid: $msg", E_USER_WARNING);
return true; // 保守假設在運行
}
return false; // 進程不存在
}
}
<?php
require 'SyncProcess.php';
// 唯一標識:建議使用路由/任務名生成唯一 PID 檔路徑
$pidFile = __DIR__ . '/data/pid/' . basename($_SERVER['SCRIPT_NAME'], '.php') . '.pid';
$sync = new SyncProcess($pidFile);
if ($sync->check()) {
exit("Process is already running\n");
}
// ===== 核心業務邏輯開始 =====
echo "Acquired lock, starting task...\n";
// 長時間運行任務:資料同步、報表生成、郵件發送...
sleep(30); // 模擬任務
echo "Task completed.\n";
// ===== 核心業務邏輯結束 =====
// 程式正常結束時,鎖會隨進程結束自動釋放
// 異常中斷(kill、Fatal Error)也會由 OS 自動釋放文件鎖
| 設計點 | 方案 | 理由 |
|---|---|---|
| 鎖類型 | flock() 文件鎖 | POSIX 標準、進程結束自動釋放、跨 NFS 需啟用 lockd |
| 非阻塞模式 | LOCK_EX | LOCK_NB | 立即返回,不阻塞調用者,適合定時任務「搶不到即退出」 |
| PID 存活驗證 | ps -o pid -p $pid | 比 kill -0 更可靠,避免權限問題;比 /proc/$pid 更可移植 |
| 死鎖恢復 | 檢測到 PID 不存在時覆寫 PID | 進程異常退出(OOM、Segfault、kill -9)不會釋放鎖,下次檢查自動恢復 |
| 原子性 | flock + 寫入 PID 在同一關鍵區 | 避免檢查-然後執行 (TOCTOU) 競態條件 |
kill -0 $pid 驗證:需發送訊號權限,容器/共享主機常失敗flock 在 NFS 上需核心支援 lockd,否則失效,改用 Redis 分佈式鎖max_execution_time 導致的強制結束class RedisLock {
private \Redis $redis;
private string $key;
private int $ttl;
private string $token;
public function __construct(\Redis $redis, string $key, int $ttl = 30) {
$this->redis = $redis;
$this->key = "lock:$key";
$this->ttl = $ttl;
$this->token = bin2hex(random_bytes(16));
}
public function acquire(): bool {
// SET key token NX EX ttl
return $this->redis->set($this->key, $this->token, ['nx', 'ex' => $this->ttl]);
}
public function release(): bool {
// Lua 腳本:僅刪除自己持有的鎖
$script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
return $this->redis->eval($script, 1, $this->key, $this->token);
}
public function extend(int $additionalTtl): bool {
$script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end";
return $this->redis->eval($script, 1, $this->key, $this->token, $this->ttl + $additionalTtl);
}
}
單機用 SyncProcess,分佈式用 RedisLock,根據部署架構選型。