PHP不適合做常駐的SHELl進程,因為它沒有專門的gc例程,也沒有有效的內存管理途徑。
如果用PHP做常駐SHELL,會經常被內存耗盡導致abort而unhappy。
而且,如果輸入數據非法,而腳本沒有檢測,導致abort。
此時可以考慮php的多進程,來幫助解決如上的問題。
使用多進程的優點:
1. 子進程結束以后, 內核會負責回收資源
2. 子進程異常退出不會導致整個進程Thread退出. 父進程還有機會重建流程.
3. 一個常駐主進程, 只負責任務分發, 邏輯更清楚.
如何使用php的多進程
使用PHP提供的POSIX和Pcntl系列函數, 來實現一個PHP命令解析器, 主進程負責接受用戶輸入, 然后fork子進程執行, 並負責回顯子進程的結束狀態.
代碼如下:
#!/bin/env php <?php /** A example denoted muti-process application in php * @filename fork.php * @edit www.jbxue.com * @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: {$return['pid']} exited with {$status}"; } } } ?>