天天看點

PHP CLI模式下的多程序應用

php在很多時候不适合做常駐的shell程序, 他沒有專門的gc例程, 也沒有有效的記憶體管理途徑. 是以如果用php做常駐shell, 你會經常被記憶體耗盡導緻abort而unhappy.

而且, 如果輸入資料非法, 而腳本沒有檢測, 導緻abort, 也會讓你很不開心.

那? 怎麼辦呢?

多程序….

為什麼呢?

 優點:

    1. 使用多程序, 子程序結束以後, 核心會負責回收資源

    2. 使用多程序,子程序異常退出不會導緻整個程序thread退出. 父程序還有機會重建流程.

    3. 一個常駐主程序, 隻負責任務分發, 邏輯更清楚.

then, 怎麼做呢?

接下來, 我們使用php提供的posix和pcntl系列函數, 來實作一個php指令解析器, 主程序負責接受使用者輸入, 然後fork子程序執行, 并負責回顯子程序的結束狀态.

#!/bin/env php

<?php

/** a example denoted muti-process application in php

* @filename fork.php

* @touch date wed 10 jun 2009 10:25:51 pm cst

* @version 1.0.0

*/

/** 確定這個函數隻能運作在shell中 */

if (substr(php_sapi_name(), 0, 3) !== 'cli') {

    die("this programe can only be run in cli mode");

}

/** 關閉最大執行時間限制, 在cli模式下, 這個語句其實不必要 */

set_time_limit(0);

$pid = posix_getpid(); //取得主程序id

$user = posix_getlogin(); //取得使用者名

echo <<<eod

usage: [command | expression]

input php code to execute by fork a new process

input quit to exit

        shell executor version 1.0.0 by laruence

eod;

while (true) {

        $prompt = "\n{$user}$ ";

        $input = readline($prompt);

        readline_add_history($input);

        if ($input == 'quit') {

               break;

          }

        process_execute($input . ';');

exit(0);

function process_execute($input) {

        $pid = pcntl_fork(); //建立子程序

        if ($pid == 0) {//子程序

                $pid = posix_getpid();

                echo "* process {$pid} was created, and executed:\n\n";

                eval($input); //解析指令

                exit;

        } else {//主程序

                $pid = pcntl_wait($status, wuntraced); //取得子程序結束狀态

                if (pcntl_wifexited($status)) {

                        echo "\n\n* sub process: {$pid} exited with {$status}";

                }

        }

但有一點, 我一定要提醒:

process control should not be enabled within a webserver environment and unexpected results may happen if any process control functions are used within a webserver environment. --摘自php手冊

也就是說, 打消你在php web開發中使用多程序的念頭吧!

http://www.laruence.com/2009/06/11/930.html