欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php 多进程解决代码常驻内存的问题

程序员文章站 2022-04-29 19:52:41
...
  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. ?>
复制代码

大家注意以上代码中的注释,可以帮助大家理解,也是代码的精粹所在哦。