守護進程在後台運行,脫離終端控制,不受用戶登入/登出影響,通常作為服務端程序持續提供服務(如隊列消費者、定時任務、Socket 服務器)。標準化守護進程需滿足:
<?php
declare(strict_types=1);
class Daemon {
private string $pidFile;
private string $logFile;
private bool $running = true;
private array $workers = [];
public function __construct(string $pidFile = '/var/run/mydaemon.pid', string $logFile = '/var/log/mydaemon.log') {
$this->pidFile = $pidFile;
$this->logFile = $logFile;
}
public function start(): void {
// 1. 檢查是否已運行
if ($this->isRunning()) {
die("守護進程已在運行 (PID: {$this->getPid()})\n");
}
// 2. 第一次 Fork:父進程退出,子進程繼續 (脫離終端控制)
$pid = pcntl_fork();
if ($pid === -1) die("First fork failed\n");
if ($pid > 0) exit(0); // 父進程退出
// 3. 子進程成為會話組長 (脫離控制終端)
if (posix_setsid() === -1) die("setsid failed\n");
// 4. 第二次 Fork:確保進程不是會話組長,無法重新獲得控制終端
$pid = pcntl_fork();
if ($pid === -1) die("Second fork failed\n");
if ($pid > 0) exit(0); // 第一子進程退出
// 5. 現在在第二子進程 (真正的守護進程)
// 切換工作目錄
chdir('/');
// 重置 umask
umask(0);
// 關閉標準流並重定向到日誌/空設備
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$stdin = fopen('/dev/null', 'r');
$stdout = fopen($this->logFile, 'a');
$stderr = fopen($this->logFile, 'a');
// 確保 fd 0,1,2 對應 stdin,stdout,stderr
// (fopen 通常會依次分配最小可用 fd)
// 6. 寫入 PID 文件 (原子操作)
$this->writePidFile();
// 7. 註冊信號處理
pcntl_async_signals(true);
pcntl_signal(SIGTERM, [$this, 'handleSignal']);
pcntl_signal(SIGINT, [$this, 'handleSignal']);
pcntl_signal(SIGHUP, [$this, 'handleSignal']); // 重新載入配置
pcntl_signal(SIGCHLD, [$this, 'handleSignal']); // 子進程結束
// 8. 主循環
$this->run();
}
private function run(): void {
$this->log("守護進程啟動 (PID: " . getmypid() . ")");
// 啟動業務 Worker (示例:固定 3 個)
for ($i = 0; $i < 3; $i++) {
$this->forkWorker($i);
}
while ($this->running) {
// 回收子進程
$this->reapChildren();
// 定期任務 (如每分鐘)
static $lastMinute = 0;
$now = time();
if ($now !== $lastMinute) {
$lastMinute = $now;
$this->periodicTask();
}
// 休眠減少 CPU 佔用
sleep(1);
}
// 關閉階段
$this->log("收到停止信號,等待 Worker 結束...");
foreach ($this->workers as $pid => $info) {
posix_kill($pid, SIGTERM);
}
// 等待所有結束
while (!empty($this->workers)) {
$this->reapChildren();
usleep(100_000);
}
// 清理 PID 文件
@unlink($this->pidFile);
$this->log("守護進程已停止");
}
private function forkWorker(int $id): void {
$pid = pcntl_fork();
if ($pid === -1) {
$this->log("Worker {$id} fork 失敗");
return;
} elseif ($pid === 0) {
// Worker 子進程
// 重新初始化資源 (DB, Redis, etc.)
$this->workerMain($id);
exit(0);
} else {
$this->workers[$pid] = ['id' => $id, 'start' => time()];
}
}
private function workerMain(int $id): void {
$this->log("Worker {$id} 啟動 (PID: " . getmypid() . ")");
// 設置 Worker 自己的信號處理 (可選)
pcntl_async_signals(true);
pcntl_signal(SIGTERM, fn() => exit(0));
while (true) {
// 從隊列獲取任務、處理業務邏輯...
// 示例:模擬工作
sleep(5);
$this->log("Worker {$id} 處理任務中...");
}
}
private function reapChildren(): void {
while (($pid = pcntl_waitpid(-1, $status, WNOHANG)) > 0) {
if (isset($this->workers[$pid])) {
$info = $this->workers[$pid];
unset($this->workers[$pid]);
$code = pcntl_wifexited($status) ? pcntl_wexitstatus($status) : -1;
$this->log("Worker {$info['id']} (PID:{$pid}) 退出,碼:{$code},自動重啟...");
// 自動重啟策略
$this->forkWorker($info['id']);
}
}
}
private function periodicTask(): void {
// 定期任務:清理緩存、檢查磁盤、報告狀態等
$this->log("定期任務執行: " . date('Y-m-d H:i:s'));
}
private function handleSignal(int $signo): void {
switch ($signo) {
case SIGTERM:
case SIGINT:
$this->running = false;
break;
case SIGHUP:
$this->log("收到 SIGHUP,重新載入配置...");
// reloadConfig();
break;
case SIGCHLD:
// 主循環會調用 reapChildren
break;
}
}
private function log(string $msg): void {
$line = "[" . date('Y-m-d H:i:s') . "] {$msg}\n";
// 直接寫入文件 (已重定向 stdout/stderr 到日誌文件)
// 或使用 error_log($line, 3, $this->logFile);
fwrite(STDOUT, $line);
}
private function writePidFile(): void {
$dir = dirname($this->pidFile);
if (!is_dir($dir)) @mkdir($dir, 0755, true);
// 原子寫入:寫臨時文件 -> rename
$tmp = $this->pidFile . '.tmp';
file_put_contents($tmp, getmypid() . "\n");
rename($tmp, $this->pidFile);
}
private function isRunning(): bool {
if (!file_exists($this->pidFile)) return false;
$pid = (int)file_get_contents($this->pidFile);
if ($pid <= 1) return false;
// 檢查進程是否存在
return posix_kill($pid, 0) === true; // 信號 0 僅檢查存在性
}
private function getPid(): int {
return (int)file_get_contents($this->pidFile);
}
public function stop(): void {
if (!$this->isRunning()) {
echo "進程未運行\n";
return;
}
$pid = $this->getPid();
posix_kill($pid, SIGTERM);
echo "已發送停止信號至 PID {$pid}\n";
}
public function status(): void {
if ($this->isRunning()) {
echo "運行中 (PID: {$this->getPid()})\n";
} else {
echo "已停止\n";
}
}
}
// ==================== 入口腳本 ====================
$daemon = new Daemon();
$action = $argv[1] ?? 'start';
switch ($action) {
case 'start': $daemon->start(); break;
case 'stop': $daemon->stop(); break;
case 'restart': $daemon->stop(); sleep(2); $daemon->start(); break;
case 'status': $daemon->status(); break;
default:
echo "用法: php daemon.php {start|stop|restart|status}\n";
exit(1);
}
?>
/etc/systemd/system/mydaemon.service[Unit]
Description=My PHP Daemon
After=network.target mysql.service redis.service
[Service]
Type=forking
PIDFile=/var/run/mydaemon.pid
ExecStart=/usr/bin/php /opt/myapp/daemon.php start
ExecStop=/usr/bin/php /opt/myapp/daemon.php stop
ExecReload=/usr/bin/php /opt/myapp/daemon.php restart
Restart=on-failure
RestartSec=5
User=www-data
Group=www-data
StandardOutput=append:/var/log/mydaemon.log
StandardError=append:/var/log/mydaemon.log
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start mydaemon
systemctl stop mydaemon
systemctl restart mydaemon
systemctl status mydaemon
systemctl enable mydaemon # 開機自啟
journalctl -u mydaemon -f # 查看日誌
| 步驟 | 系統調用 | 作用 | 不做的後果 |
|---|---|---|---|
| 第一次 Fork | fork() | 父進程退出,Shell 以為命令結束;子進程在後台繼續 | 前台佔用終端,關閉終端進程收到 SIGHUP 退出 |
| setsid() | setsid() | 創建新會話,進程成為會話組長,失去控制終端 | 進程仍關聯舊終端,可能收到終端信號 |
| 第二次 Fork | fork() | 確保進程不是會話組長,永無法重新獲得控制終端 | 理論上可能通過打開終端設備重獲控制權 |
| chdir('/') | chdir() | 避免鎖定掛載點導致無法 umount | 若工作目錄在掛載點,該分區無法卸載 |
| umask(0) | umask() | 確保創建文件權限由代碼完全控制 | 繼承父進程 umask,可能導致權限過寬/過窄 |
| 關閉標準流 | close/open | 釋放終端文件描述符,防止輸出干擾/阻塞 | 輸出可能卡住、日誌混亂、安全洩露 |
PHP 實現守護進程的標準模式是 雙重 Fork + setsid + 資源隔離 + 信號處理 + PID 文件。雖然現代部署多交由 Systemd/Supervisor/Docker 管理,但理解底層原理對排查進程異常退出、殭屍進程、信號處理失效等問題至關重要。生產環境建議:業務邏輯寫為前台長運行腳本,交由 Systemd/Supervisor 守護,避免在 PHP 代碼中手動實現複雜的守護化邏輯。