PHP在不少時候不適合作常駐的SHELL進程, 他沒有專門的gc例程, 也沒有有效的內存管理途徑. 因此若是用PHP作常駐SHELL, 你會常常被內存耗盡致使abort而unhappy.php
並且, 若是輸入數據非法, 而腳本沒有檢測, 致使abort, 也會讓你很不開心.html
那? 怎麼辦呢?web
多進程….express
爲何呢?api
- 優勢:
- 1. 使用多進程, 子進程結束之後, 內核會負責回收資源
- 2. 使用多進程,子進程異常退出不會致使整個進程Thread退出. 父進程還有機會重建流程.
- 3. 一個常駐主進程, 只負責任務分發, 邏輯更清楚.
Then, 怎麼作呢?app
接下來, 咱們使用PHP提供的POSIX和Pcntl系列函數, 來實現一個PHP命令解析器, 主進程負責接受用戶輸入, 而後fork子進程執行, 並負責回顯子進程的結束狀態.函數
代碼以下, 我加了註釋, 若是有不懂的地方, 能夠翻閱手冊相關函數, 或者回覆留言.ui
- <?php
-
- if (substr(php_sapi_name(), 0, 3) !== 'cli') {
- die("This Programe can only be run in CLI mode");
- }
-
- set_time_limit(0);
-
- $pid = posix_getpid();
- $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}";
- }
- }
- }
-
但有一點, 我必定要提醒:google
- 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開發中使用多進程的念頭吧!url