工作,学习,生活,这里将会有一些记录. 备用域名:http://meisw.wdlinux.cn 注册 | 登陆

php命令行,多进程

  1. /** 确保这个函数只能运行在SHELL中 */
  2. if (substr(php_sapi_name(), 0, 3) !== 'cli') {
  3.     die("This Programe can only be run in CLI mode");
  4. }
  5.  
  6. /** 关闭最大执行时间限制, 在CLI模式下, 这个语句其实不必要 */
  7. set_time_limit(0);
  8.  
  9. $pid = posix_getpid(); //取得主进程ID
  10. $user = posix_getlogin(); //取得用户名
  11.  
  12. echo <<<EOD
  13. USAGE: [command | expression]
  14. input php code to execute by fork a new process
  15. input quit to exit
  16.  
  17.         Shell Executor version 1.0.0 by laruence
  18. EOD;
  19.  
  20. while (true) {
  21.  
  22.         $prompt = "\n{$user}$ ";
  23.         $input = readline($prompt);
  24.  
  25.         readline_add_history($input);
  26.         if ($input == 'quit') {
  27.                break;
  28.           }
  29.         process_execute($input . ';');
  30. }
  31.  
  32. exit(0);
  33.  
  34. function process_execute($input) {
  35.         $pid = pcntl_fork(); //创建子进程
  36.         if ($pid == 0) {//子进程
  37.                 $pid = posix_getpid();
  38.                 echo "* Process {$pid} was created, and Executed:\n\n";
  39.                 eval($input); //解析命令
  40.                 exit;
  41.         } else {//主进程
  42.                 $pid = pcntl_wait($status, WUNTRACED); //取得子进程结束状态
  43.                 if (pcntl_wifexited($status)) {
  44.                         echo "\n\n* Sub process: {$pid} exited with {$status}";
  45.                 }
  46.         }
  47. }

 

http://www.laruence.com/2009/06/11/930.html

« 上一篇 | 下一篇 »

Trackbacks

点击获得Trackback地址,Encode: UTF-8

发表评论

评论内容 (必填):