PHP CLI模式下的多進程應用

PHP在不少時候不適合作常駐的SHELL進程, 他沒有專門的gc例程, 也沒有有效的內存管理途徑. 因此若是用PHP作常駐SHELL, 你會常常被內存耗盡致使abort而unhappy.php

並且, 若是輸入數據非法, 而腳本沒有檢測, 致使abort, 也會讓你很不開心.html

那? 怎麼辦呢?web

多進程….express

爲何呢?api

  1.  優勢:
  2.     1. 使用多進程, 子進程結束之後, 內核會負責回收資源
  3.     2. 使用多進程,子進程異常退出不會致使整個進程Thread退出. 父進程還有機會重建流程.
  4.     3. 一個常駐主進程, 只負責任務分發, 邏輯更清楚.

 

Then, 怎麼作呢?app

接下來, 咱們使用PHP提供的POSIX和Pcntl系列函數, 來實現一個PHP命令解析器, 主進程負責接受用戶輸入, 而後fork子進程執行, 並負責回顯子進程的結束狀態.函數

代碼以下, 我加了註釋, 若是有不懂的地方, 能夠翻閱手冊相關函數, 或者回覆留言.ui

  1. #!/bin/env php
  2. <?php
  3. /** A example denoted muti-process application in php
  4. * @filename fork.php
  5. * @touch date Wed 10 Jun 2009 10:25:51 PM CST
  6. * @author Laruence<laruence@baidu.com>
  7. * @license http://www.zend.com/license/3_0.txt PHP License 3.0
  8. * @version 1.0.0
  9. */
  10.  
  11. /** 確保這個函數只能運行在SHELL中 */
  12. if (substr(php_sapi_name(), 0, 3) !== 'cli') {
  13.     die("This Programe can only be run in CLI mode");
  14. }
  15.  
  16. /** 關閉最大執行時間限制, 在CLI模式下, 這個語句其實沒必要要 */
  17. set_time_limit(0);
  18.  
  19. $pid = posix_getpid(); //取得主進程ID
  20. $user = posix_getlogin(); //取得用戶名
  21.  
  22. echo <<<EOD
  23. USAGE: [command | expression]
  24. input php code to execute by fork a new process
  25. input quit to exit
  26.  
  27.         Shell Executor version 1.0.0 by laruence
  28. EOD;
  29.  
  30. while (true) {
  31.  
  32.         $prompt = "\n{$user}$ ";
  33.         $input = readline($prompt);
  34.  
  35.         readline_add_history($input);
  36.         if ($input == 'quit') {
  37.                break;
  38.           }
  39.         process_execute($input . ';');
  40. }
  41.  
  42. exit(0);
  43.  
  44. function process_execute($input) {
  45.         $pid = pcntl_fork(); //建立子進程
  46.         if ($pid == 0) {//子進程
  47.                 $pid = posix_getpid();
  48.                 echo "* Process {$pid} was created, and Executed:\n\n";
  49.                 eval($input); //解析命令
  50.                 exit;
  51.         } else {//主進程
  52.                 $pid = pcntl_wait($status, WUNTRACED); //取得子進程結束狀態
  53.                 if (pcntl_wifexited($status)) {
  54.                         echo "\n\n* Sub process: {$pid} exited with {$status}";
  55.                 }
  56.         }
  57. }
  58.   

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

  1. 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

相關文章
相關標籤/搜索