萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP CLI 守護進程實作:pcntl_fork 雙重 Fork 脫離終端完整教學

什麼是守護進程?

守護進程在背景運行、脫離終端、無控制終端、通常以 root 或專用用戶身份運行、生命週期獨立於登入會話。常見:Nginx、MySQL、Redis、PHP Worker、排程器。

為什麼需要雙重 Fork?

  1. 第一次 Fork:父進程退出,子進程成為孤兒進程,被 init (PID 1) 收養,脫離原終端控制
  2. setsid():子進程建立新會話,成為會話領導者,**失去控制終端**
  3. 第二次 Fork:防止會話領導者重新獲得控制終端(某些系統允許會話領導者開啟終端),第二子進程不再是會話領導者,徹底脫離終端

完整生產級實作

<?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;
}
?>

實際 Worker 範例

<?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"
};
?>

系統層面部署:Systemd 服務單元

# /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 環境

關鍵注意事項

  • ❌ Windows 不支援 pcntl:開發環境用 Docker/Linux VM
  • ⚠️ 資料庫連線:Fork 後子進程共享父進程連線,必須在子進程重新連線
  • ⚠️ 檔案描述符洩漏:Fork 前關閉不需要的連線、句柄
  • ⚠️ 信號處理:必須註冊 SIGCHLD 回收子進程,否則產生殭屍進程
  • ✅ 優雅關機:SIGTERM -> 完成當前工作 -> 退出
  • ✅ 日誌輪轉:logrotate 配合 copytruncate 或信號觸發重開

守護進程是 PHP 進入長運行服務領域的關鍵技能。掌握雙重 Fork 原理、善用 Supervisor/Systemd 管理,能讓 PHP 處理百萬級隊列任務、WebSocket 服務、定時排程等場景。

copyright © 萬盛學電腦網 all rights reserved