PHP CLI模式下的多進程應用

來源:互聯網
上載者:User

   PHP在很多時候不適合做常駐的SHELl進程, 他沒有專門的gc常式, 也沒有有效記憶體管理途徑. 所以如果用PHP做常駐SHELL, 你會經常被記憶體耗盡導致abort而unhappy.

  而且, 如果輸入資料非法, 而指令碼沒有檢測, 導致abort, 也會讓你很不開心.

  那? 怎麼辦呢?

  呵呵, 別著急, 多進程來幫您!

  那,這是為什麼呢?

  優點:

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

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

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

  Then, 怎麼做呢?

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

  代碼如下, 我加了注釋, 如果有不懂的地方, 可以翻閱手冊相關函數, 或者回複留言.

  #!/bin/env php

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

  * @filename fork.php

  * @touch date Wed 10 Jun 2009 10:25:51 PM CST

  * @author Laruence

  * @license http://www.zend.com/license/3_0.txt   PHP License 3.0

  * @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

  <<

  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:nn";

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

  exit;

  }

  else

  {//主進程

  $pid = pcntl_wait($status, WUNTRACED); //取得子進程結束狀態

  if

  (pcntl_wifexited($status))

  {

  echo

  "nn* Sub process: {$return['pid']} exited with {$status}";

  }

  }

  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.