DIV CSS 佈局教程網

PHP 實現守護進程的實例解析
編輯:JavaScript基礎知識     

PHP 也能直接進行守護進程的啟動與終止,相比 Shell 會簡單許多,也更易理解。不過,PHP 守護進程要實現自動重啟,仍需依賴 Shell 的 crontab 日程表:每隔一段時間執行一次腳本,檢查腳本是否需要重啟;若需要,就殺掉進程、刪除 RunFile 文件,重新啟動並把 pid 寫入 RunFile 文件中。

<?php
function start($file) {
    $path = dirname(__FILE__) . '/';
    $runfile = $path . $file . '.run';
    $diefile = $path . $file . '.die';
    $file = $path . "data/{$file}.php";
    clearstatcache();
    if (file_exists($runfile)) {
        $oldpid = file_get_contents($runfile);
        $nowpid = shell_exec("ps aux | grep 'php -f process.php' | grep ${oldpid} | awk '{print $2}'");
        // 若 runfile 中的 pid 能匹配到正在運行的進程,且上次訪問 runfile 至今小於 5 分鐘,則返回
        if (($oldpid == $nowpid) && (time() - fileatime($runfile) < 300)) {
            echo "$file is circle runing no";
            return;
        } else {
            // pid 不匹配或已超過 300 秒未循環,直接殺掉進程並重啟
            $pid = file_get_contents($runfile);
            shell_exec("ps aux | grep 'php -f process.php' | grep {$pid} | xargs --if-no-run-empty kill");
        }
    } else {
        // 把 pid 寫入 run 文件
        if (!($newpid = getmypid()) || !file_put_contents($runfile, $newpid)) {
            return;
        }
        while (true) {
            // 收到結束進程信號,結束進程並刪除相關文件
            if (file_exists($diefile) && unlink($runfile) && unlink($diefile)) {
                return;
            }
            /* 這裡是守護進程要做的事 */
            file_put_contents($file, "I'm Runing Now" . PHP_EOL, FILE_APPEND);
            /***********************/
            touch($runfile);
            sleep(5);
        }
    }
}
start("test");

用 PHP 撰寫守護進程時,有幾點值得特別留意:

1. 關於 clearstatcache()
查官方手冊可知,該函式用於清除文件狀態緩存。當在一個腳本中多次檢查同一文件的緩存狀態時,若不使用它就可能出錯。受此函式影響的還有:stat()、lstat()、file_exists()、is_writable()、is_readable()、is_executable()、is_file()、is_dir()、is_link()、filectime()、fileatime()、filemtime()、fileinode()、filegroup()、fileowner()、filesize()、filetype()、fileperms() 等。

2. 進程健康檢測
多次運行該腳本時,會在啟動前進行檢測:若上次執行循環距今超過 300 秒,或 pid 號不匹配,都會重啟進程(每次循環時都要用 touch 更新時間)。

3. 借助 crontab 實現自動重啟
把該文件加入 crontab 日程表:

crontab -e
# 打開日程表,進入 inset 模式

*/3 * * * * /usr/bin/php -f process.php
# 每 3 分鐘執行一次,防止進程掛掉

這樣基本就能實現守護進程的自動保活。若要接入具體業務功能,還需相應改動程式碼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved