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. <<
  19. USAGE: [command | expression]
  20. input php code to execute by fork a new process
  21. input quit to exit
  22. Shell Executor version 1.0.0 by laruence
  23. EOD;
  24. while
  25. (true)
  26. {
  27. $prompt = "\n{$user}$ ";
  28. $input = readline($prompt);
  29. readline_add_history($input);
  30. if
  31. ($input == 'quit')
  32. {
  33. break;
  34. }
  35. process_execute($input . ';');
  36. }
  37. exit(0);
  38. function
  39. process_execute($input)
  40. {
  41. $pid = pcntl_fork(); //建立子進程
  42. if
  43. ($pid == 0)
  44. {//子進程
  45. $pid = posix_getpid();
  46. echo
  47. "* Process {$pid} was created, and Executed:\n\n";
  48. eval($input); //解析命令
  49. exit;
  50. }
  51. else
  52. {//主進程
  53. $pid = pcntl_wait($status, WUNTRACED); //取得子進程結束狀態
  54. if
  55. (pcntl_wifexited($status))
  56. {
  57. echo
  58. "\n\n* Sub process: {$return['pid']} exited with {$status}";
  59. }
  60. }
  61. }
  62. ?>
複製代碼

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

  • 聯繫我們

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