守護進程在背景運行、脫離終端、無控制終端、通常以 root 或專用用戶身份運行、生命週期獨立於登入會話。常見:Nginx、MySQL、Redis、PHP Worker、排程器。
<?php
/**
* PHP 守護進程基類
* 需要:php.ini 啟用 pcntl、posix 擴充
*/
abstract class Daemon
{
protected string $pidFile;
protected string $logFile;
protected int $maxChildren = 1;
protected array $children = [];
protected bool $running = false;
public function __construct(string $pidFile, string $logFile = '/var/log/daemon.log')
{
$this->pidFile = $pidFile;
$this->logFile = $logFile;
}
public function start(): void
{
if ($this->isRunning()) {
$this->log("Daemon already running (PID: {$this->getPid()})");
exit(1);
}
$this->daemonize();
$this->writePid();
$this->setupSignals();
$this->running = true;
$this->log("Daemon started (PID: " . getmypid() . ")");
$this->run();
}
public function stop(): void
{
$pid = $this->getPid();
if (!$pid) {
$this->log("Daemon not running");
return;
}
posix_kill($pid, SIGTERM);
$this->log("Stop signal sent to PID: $pid");
}
public function restart(): void
{
$this->stop();
sleep(2);
$this->start();
}
public function status(): void
{
if ($this->isRunning()) {
echo "Running (PID: {$this->getPid()})\n";
} else {
echo "Stopped\n";
}
}
// === 核心:雙重 Fork 脫離終端 ===
private function daemonize(): void
{
// 第一次 Fork
$pid = pcntl_fork();
if ($pid === -1) {
throw new RuntimeException('First fork failed');
} elseif ($pid > 0) {
exit(0); // 父進程退出
}
// 脫離終端:建立新會話
if (posix_setsid() === -1) {
throw new RuntimeException('setsid failed');
}
// 第二次 Fork
$pid = pcntl_fork();
if ($pid === -1) {
throw new RuntimeException('Second fork failed');
} elseif ($pid > 0) {
exit(0); // 第一子進程退出
}
// 現在是第二子進程:真正的守護進程
umask(0); // 重設檔案權限遮罩
chdir('/'); // 切換到根目錄,避免掛載點被佔用
// 關閉標準輸入輸出(可選:重導向到日誌檔)
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$logFp = fopen($this->logFile, 'a');
if ($logFp) {
$fd = (int)$logFp;
// 可選:dup2 到 STDIN/OUT/ERR
}
}
private function writePid(): void
{
file_put_contents($this->pidFile, getmypid());
register_shutdown_function(fn() => @unlink($this->pidFile));
}
private function getPid(): ?int
{
if (!file_exists($this->pidFile)) return null;
$pid = (int)file_get_contents($this->pidFile);
return posix_kill($pid, 0) ? $pid : null; // 信號 0 只檢查進程是否存在
}
private function isRunning(): bool
{
return $this->getPid() !== null;
}
private function setupSignals(): void
{
pcntl_signal(SIGTERM, [$this, 'handleSignal']);
pcntl_signal(SIGINT, [$this, 'handleSignal']);
pcntl_signal(SIGHUP, [$this, 'handleSignal']);
pcntl_signal(SIGCHLD, [$this, 'handleSignal']);
}
public function handleSignal(int $signo): void
{
switch ($signo) {
case SIGTERM:
case SIGINT:
$this->log("Received stop signal ($signo)");
$this->running = false;
break;
case SIGHUP:
$this->log("Received reload signal");
$this->reloadConfig();
break;
case SIGCHLD:
// 回收子進程,避免殭屍進程
while (($pid = pcntl_waitpid(-1, $status, WNOHANG)) > 0) {
$this->log("Child $pid exited with status $status");
unset($this->children[$pid]);
}
break;
}
}
protected function log(string $message): void
{
$line = date('Y-m-d H:i:s') . " [" . getmypid() . "] $message\n";
file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
}
protected function reloadConfig(): void
{
// 子類實作:重新讀取配置
}
abstract protected function run(): void;
}
?>
<?php
require 'Daemon.php';
class QueueWorker extends Daemon
{
protected int $maxChildren = 5;
private PDO $pdo;
protected function run(): void
{
$this->pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
while ($this->running) {
// 維持子進程數量
while (count($this->children) < $this->maxChildren && $this->running) {
$this->forkWorker();
}
// 等待信號或子進程結束
pcntl_signal_dispatch();
sleep(1);
}
// 等待所有子進程結束
while ($this->children) {
pcntl_signal_dispatch();
sleep(1);
}
$this->log("All workers stopped, daemon exiting");
}
private function forkWorker(): void
{
$pid = pcntl_fork();
if ($pid === -1) {
$this->log("Fork worker failed");
return;
} elseif ($pid > 0) {
// 父進程:記錄子進程
$this->children[$pid] = true;
return;
}
// 子進程:執行工作
$this->log("Worker started");
$this->processJobs();
exit(0);
}
private function processJobs(): void
{
while ($this->running) {
$stmt = $this->pdo->prepare('SELECT * FROM jobs WHERE status="pending" ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED');
$stmt->execute();
$job = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$job) {
sleep(5);
continue;
}
try {
$this->executeJob($job);
$this->pdo->prepare('UPDATE jobs SET status="done", finished_at=NOW() WHERE id=?')->execute([$job['id']]);
} catch (Throwable $e) {
$this->pdo->prepare('UPDATE jobs SET status="failed", error=? WHERE id=?')->execute([$e->getMessage(), $job['id']]);
}
}
}
private function executeJob(array $job): void
{
// 實際業務邏輯
$this->log("Processing job {$job['id']}: {$job['payload']}");
}
}
// === 啟動腳本 ===
$worker = new QueueWorker('/var/run/queue_worker.pid', '/var/log/queue_worker.log');
$action = $argv[1] ?? 'start';
match ($action) {
'start' => $worker->start(),
'stop' => $worker->stop(),
'restart' => $worker->restart(),
'status' => $worker->status(),
default => echo "Usage: php worker.php {start|stop|restart|status}\n"
};
?>
# /etc/systemd/system/queue-worker.service
[Unit]
Description=PHP Queue Worker
After=network.target mysql.service redis.service
[Service]
Type=forking
User=www-data
Group=www-data
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/php /var/www/app/worker.php start
ExecStop=/usr/bin/php /var/www/app/worker.php stop
ExecReload=/usr/bin/php /var/www/app/worker.php restart
PIDFile=/var/run/queue_worker.pid
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
# 啟用並啟動
systemctl daemon-reload
systemctl enable queue-worker
systemctl start queue-worker
systemctl status queue-worker
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| PHP pcntl 雙重 Fork | 純 PHP、無外部依賴、完全控制 | 需 pcntl 擴充、Windows 不支援、複雜度高 | Linux 專用、高併發 Worker |
| nohup php script.php & | 極簡單、無需修改代碼 | 無進程管理、無自動重啟、日誌混雜 | 臨時腳本、測試 |
| Supervisor | 成熟進程管理、Web UI、自動重啟、日誌分離 | 需安裝 Python/Supervisor | 生產環境首選 |
| Systemd | 系統級、無額外依賴、Socket 啟動、資源限制 | 配置較複雜、需 root 權限安裝 | 現代 Linux 標準部署 |
| Docker + 入口腳本 | 容器化、隔離、編排友善 | 需容器基礎設施 | 雲原生、K8s 環境 |
守護進程是 PHP 進入長運行服務領域的關鍵技能。掌握雙重 Fork 原理、善用 Supervisor/Systemd 管理,能讓 PHP 處理百萬級隊列任務、WebSocket 服務、定時排程等場景。