萬盛學電腦網

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

使用 PHP 編寫 Daemon 守護進程:從原理到 Gearman Worker 實戰

什麼是 Daemon 進程?

Daemon(守護進程/精靈進程) 是在後台長期運行、不與任何終端關聯、不受用戶登入/登出影響的系統服務進程。典型特徵:

  • **生命週期長**:系統啟動即啟動,關機才結束
  • **無控制終端**:脫離終端,關閉終端不影響運行
  • **後台運行**:無前台交互介面
  • **常駐記憶體**:如 Apache、Nginx、MySQL、Redis、PHP-FPM 皆為 Daemon

Daemon 進程標準化鍛造流程 (POSIX 標準)

將普通進程「守護化」需嚴格遵循 5 步驟(雙 Fork 法為黃金標準):

步驟 1:First Fork + 父進程退出

$pid = pcntl_fork();
if ($pid > 0) { exit(0); } // 父進程退出,Shell 以為任務結束
if ($pid < 0) { die('fork failed'); }
// 子進程繼續:不再是進程組組長,為 setsid 鋪路

目的:
① 欺騙 Shell 任務已結束
② 確保子進程非進程組組長(setsid 前提)

步驟 2:setsid() 創建新會話

if (posix_setsid() === -1) { die('setsid failed'); }

效果:
① 成為新會話組長
② 脫離原會話控制
③ 脫離原進程組控制
④ **脫離控制終端控制** —— 核心關鍵

步驟 3:Second Fork (可選但推薦)

$pid = pcntl_fork();
if ($pid > 0) { exit(0); } // 第一子進程退出
// 第二子進程:確保不能重新獲得控制終端(因非會話組長)

雙 Fork 確保 Daemon **永遠無法重新獲得控制終端**,達到完全脫離。

步驟 4:切換工作目錄到根目錄

chdir('/'); // 防止掛載點無法卸載

步驟 5:重設文件權限掩碼 & 關閉標準流

umask(0); // 不屏蔽任何權限
// 關閉 stdin(0), stdout(1), stderr(2)
fclose(STDIN); fclose(STDOUT); fclose(STDERR);
// 可選:重導向到 /dev/null 或日誌檔
$null = fopen('/dev/null', 'w');
fwrite($null, ''); // 觸發 fd 分配
// 現在 fd 0,1,2 指向 /dev/null

PHP 實作完整 Daemon 骨架

<?php
declare(ticks=1); // 允許信號處理

class Daemon
{
    private $pidFile;
    private $logFile;

    public function __construct(string $pidFile, string $logFile)
    {
        $this->pidFile = $pidFile;
        $this->logFile = $logFile;
    }

    public function start(): void
    {
        if ($this->isRunning()) {
            $this->log("Daemon already running (PID: {$this->getPid()})");
            return;
        }

        // === 雙 Fork 鍛造 Daemon ===
        // Fork 1
        $pid = pcntl_fork();
        if ($pid > 0) exit(0); // 父退出
        if ($pid < 0) die("Fork #1 failed");

        // 脫離終端
        if (posix_setsid() === -1) die("setsid failed");

        // Fork 2 (確保無法重獲終端)
        $pid = pcntl_fork();
        if ($pid > 0) exit(0); // 第一子退出
        if ($pid < 0) die("Fork #2 failed");

        // 環境重設
        chdir('/');
        umask(0);
        $this->redirectStdStreams();

        // 寫入 PID 檔
        file_put_contents($this->pidFile, getmypid());

        // 信號處理
        pcntl_signal(SIGTERM, [$this, 'signalHandler']);
        pcntl_signal(SIGHUP,  [$this, 'signalHandler']);
        pcntl_signal(SIGUSR1, [$this, 'signalHandler']);

        // 主循環
        $this->log("Daemon started (PID: " . getmypid() . ")");
        $this->run();
    }

    private function redirectStdStreams(): void
    {
        fclose(STDIN); fclose(STDOUT); fclose(STDERR);
        $null = fopen('/dev/null', 'r+');
        // fd 0,1,2 自動指向 /dev/null
    }

    protected function run(): void
    {
        while (true) {
            $this->doWork();
            sleep(1); // 防佔滿 CPU
            pcntl_signal_dispatch(); // 處理信號
        }
    }

    protected function doWork(): void
    {
        // 子類實作具體業務邏輯
    }

    public function signalHandler(int $signo): void
    {
        switch ($signo) {
            case SIGTERM:
                $this->log("Received SIGTERM, shutting down gracefully...");
                $this->shutdown();
                break;
            case SIGHUP:
                $this->log("Received SIGHUP, reloading config...");
                $this->reloadConfig();
                break;
            case SIGUSR1:
                $this->log("Received SIGUSR1, custom action...");
                break;
        }
    }

    protected function shutdown(): void
    {
        @unlink($this->pidFile);
        $this->log("Daemon stopped.");
        exit(0);
    }

    protected function reloadConfig(): void { /* 子類實作 */ }

    private function log(string $msg): void
    {
        $line = date('Y-m-d H:i:s') . " [$msg]\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }

    private function isRunning(): bool
    {
        if (!file_exists($this->pidFile)) return false;
        $pid = (int)file_get_contents($this->pidFile);
        return posix_kill($pid, 0); // 信號 0 只檢查進程是否存在
    }

    private function getPid(): int
    {
        return (int)file_get_contents($this->pidFile);
    }
}

// --- 繼承實作具體業務 ---
class MyWorker extends Daemon
{
    protected function doWork(): void
    {
        // 實際任務:處理隊列、監控、定時任務等
        // 例如:$job = $this->gearmanClient->getJob(); ...
    }

    protected function reloadConfig(): void
    {
        // 重新讀取配置檔、重新連接 DB 等
    }
}

// --- 啟動入口 ---
$daemon = new MyWorker('/var/run/myworker.pid', '/var/log/myworker.log');
$daemon->start();
?>

實戰:Gearman Worker 守護進程優化

原文場景:Gearman Worker 長期運行,面臨兩大痛點:

  1. **代碼修改後如何熱重啟?**
  2. **重啟時如何確保當前任務完成才退出?**

解決方案:信號 + 配置檔 MD5 監控 + 任務狀態旗標

<?php
declare(ticks=1);

class GearmanDaemonWorker extends Daemon
{
    private $worker;
    private $configFile;
    private $configMd5;
    private $jobRunning = false;   // 當前是否有任務在跑
    private $shutdownRequested = false; // 收到關閉信號

    public function __construct(string $configFile, string $pidFile, string $logFile)
    {
        parent::__construct($pidFile, $logFile);
        $this->configFile = $configFile;
        $this->configMd5 = md5_file($configFile);
    }

    protected function run(): void
    {
        // 初始化 Gearman Worker
        $this->worker = new GearmanWorker();
        $this->worker->addServer('127.0.0.1', 4730);
        $this->worker->addFunction('my_task', [$this, 'processTask']);

        $this->log("Gearman Worker started, waiting for jobs...");

        while (!$this->shutdownRequested) {
            // 1. 檢查配置檔變更
            if (md5_file($this->configFile) !== $this->configMd5) {
                $this->log("Config file changed, requesting graceful restart...");
                $this->shutdownRequested = true;
                break;
            }

            // 2. 非阻塞檢查任務 (work() 會阻塞直到有任務)
            // 技巧:設定 timeout 實現非阻塞輪詢
            $this->worker->work(); // 這裡會阻塞,收到任務才返回

            // 3. 任務結束後,檢查是否需關閉
            if ($this->shutdownRequested && !$this->jobRunning) {
                break;
            }
        }

        $this->shutdown();
    }

    public function processTask(GearmanJob $job): string
    {
        $this->jobRunning = true;
        $this->log("Processing job: {$job->handle()}");

        try {
            // 實際業務邏輯
            $result = $this->doBusinessLogic($job->workload());
            $this->log("Job completed: {$job->handle()}");
            return $result;
        } catch (Throwable $e) {
            $this->log("Job failed: " . $e->getMessage());
            return "ERROR: " . $e->getMessage();
        } finally {
            $this->jobRunning = false;
            // 任務結束,若收到關閉信號,主循環將退出
        }
    }

    public function signalHandler(int $signo): void
    {
        switch ($signo) {
            case SIGTERM:
            case SIGINT:
                $this->log("Received stop signal, waiting for current job to finish...");
                $this->shutdownRequested = true;
                // 若無任務在跑,主循環下輪即退出
                // 若有任務,等任務結束後退出
                break;
            case SIGHUP:
                $this->log("Received SIGHUP (graceful restart), waiting for current job...");
                $this->shutdownRequested = true; // 同樣優雅退出,由外部監控器 (systemd/supervisor) 重啟
                break;
        }
    }

    private function doBusinessLogic(string $data): string
    {
        // 你的業務代碼
        sleep(2); // 模擬耗時任務
        return "Processed: $data";
    }
}

// 啟動
$worker = new GearmanDaemonWorker('/etc/myworker/config.php', '/var/run/gearman_worker.pid', '/var/log/gearman_worker.log');
$worker->start();
?>

生產環境部署建議

1. 使用進程管理器 (推薦)

**不要**寫複雜的 init.d 腳本。使用成熟工具:

  • Systemd (現代 Linux 標準):Type=notify、Restart=on-failure、WatchdogSec
  • Supervisor (跨平台、Python 寫、Web UI):autorestart=true、redirect_stderr=true
  • PHP-FPM 模式:若任務可拆分為短命請求,直接用 PHP-FPM + Nginx 更簡單

2. Systemd 服務單元範例

# /etc/systemd/system/gearman-worker.service
[Unit]
Description=Gearman PHP Worker
After=network.target gearmand.service

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/php /var/www/myapp/worker.php
Restart=on-failure
RestartSec=5
StandardOutput=append:/var/log/gearman-worker.log
StandardError=append:/var/log/gearman-worker.log
# 優雅關閉
ExecStop=/bin/kill -s TERM $MAINPID
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target

3. 關鍵 PHP 配置 (php.ini)

; 必須啟用
pcntl.enable = On
; 禁用危險函數 (若不需要)
disable_functions = pcntl_exec,pcntl_fork,pcntl_signal,posix_kill,posix_setsid,posix_getpid
; 但 Daemon 必需以上函數,請勿禁用

; 記憶體限制
memory_limit = 256M
; 最大執行時間 0 = 無限制 (Daemon 必需)
max_execution_time = 0

常見坑點與避雷指南

坑點後果解決方案
單 Fork 未做 Second Fork進程可能重新獲得控制終端嚴格執行雙 Fork
未關閉 STDIN/OUT/ERR檔案描述符洩漏、掛載點無法卸載、日誌汙染重導向至 /dev/null 或日誌檔
未處理 SIGCHLD產生殭屍進程 (若有子進程)pcntl_signal(SIGCHLD, SIG_IGN) 或 waitpid
記憶體洩漏長期運行記憶體暴漲 OOM Kill定期重啟、監控記憶體、避免全局變數累積
阻塞式 work() 無法響應信號無法優雅關閉、配置熱更失效用非阻塞輪詢或信號中斷系統調用 (pcntl_signal_dispatch)
PHP 版本不支援 pcntl (Windows)無法運行Windows 用 NSSM + PHP CLI 循環,或遷移至 Linux/Docker

結語

編寫 PHP Daemon 不是「寫個 while(true) 死循環」那麼簡單。**標準化的雙 Fork 脫離終端、信號驅動的優雅生命週期管理、配合 Systemd/Supervisor 進行生產級部署**,才是專業 PHP 後端工程師應具備的核心技能。Gearman Worker 等長連接服務型任務,更需在「任務原子性」與「進程可控性」間找到平衡——**信號 + 狀態旗標 + 外部進程管理器** 是經得起時間考驗的架構模式。

copyright © 萬盛學電腦網 all rights reserved