php 多進程解決代碼常駐記憶體的問題

來源:互聯網
上載者:User
  1. #!/bin/env php
  2. /** A example denoted muti-process application in php
  3. * @filename fork.php
  4. * @edit bbs.it-home.org
  5. * @version 1.0.0
  6. */
  7. /** 確保這個函數只能運行在SHELL中 */
  8. if
  9. (substr(php_sapi_name(), 0, 3) !== 'cli')
  10. {
  11. die("This Programe can only be run in CLI mode");
  12. }
  13. /** 關閉最大執行事件節流, 在CLI模式下, 這個語句其實不必要 */
  14. set_time_limit(0);
  15. $pid = posix_getpid(); //取得主進程ID
  16. $user = posix_getlogin(); //取得使用者名稱
  17. echo
  18. <<USAGE: [command | expression]
  19. input php code to execute by fork a new process
  20. input quit to exit
  21. Shell Executor version 1.0.0 by laruence
  22. EOD;
  23. while
  24. (true)
  25. {
  26. $prompt = "\n{$user}$ ";
  27. $input = readline($prompt);
  28. readline_add_history($input);
  29. if
  30. ($input == 'quit')
  31. {
  32. break;
  33. }
  34. process_execute($input . ';');
  35. }
  36. exit(0);
  37. function
  38. process_execute($input)
  39. {
  40. $pid = pcntl_fork(); //建立子進程
  41. if
  42. ($pid == 0)
  43. {//子進程
  44. $pid = posix_getpid();
  45. echo
  46. "* Process {$pid} was created, and Executed:\n\n";
  47. eval($input); //解析命令
  48. exit;
  49. }
  50. else
  51. {//主進程
  52. $pid = pcntl_wait($status, WUNTRACED); //取得子進程結束狀態
  53. if
  54. (pcntl_wifexited($status))
  55. {
  56. echo
  57. "\n\n* Sub process: {$return['pid']} exited with {$status}";
  58. }
  59. }
  60. }
  61. ?>
複製代碼

大家注意以上代碼中的注釋,可以協助大家理解,也是代碼的精粹所在哦。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.