一个用于消息队列的并发式php进程管理程序-进程
本程序是一个消息队列的守护进程,用于读取消息队列的消息,并启动相应的进程进行消息的处理的并发式php进程管理程序。
进程类
用来封装被管理的进程的信息。
进程里开辟了linux的双向管道,可以进行进程数据的通信。
1 class Process { 2 private $_resource = null; 3 private $_pipes = array(); 4 private $_script = ''; 5 private $_max_exec_time = 30; 6 private $_start_time = 0; 7 8 private $_error = ''; 9 public $message_id = ''; 10 11 function __construct(&$executable, $script, $params) { 12 $this->_script = $script; 13 $this->_max_exec_time = $params['max_exec_time']; 14 $this->message_id = $params['message_id']; 15 $descriptorspec = array( 16 0 => array('pipe', 'r'), // in 17 1 => array('pipe', 'w'), // out 18 2 => array('pipe', 'w') // err 19 ); 20 _print_log("start process ..."); 21 $this->_resource = proc_open($executable." ".$this->_script, $descriptorspec, $this->_pipes); 22 $this->_start_time = time(); 23 if ( is_resource($this->_resource) ) { 24 25 // print process status 26 $status = proc_get_status($this->_resource); 27 _print_log("process_status:".var_export($status, true)); 28 29 // write param to process 30 if ( !empty($params['params']) ) { 31 $data = is_string($params['params'])? $params['params']:serialize($params['params']); 32 fwrite($this->_pipes[IO::IN], $data); 33 } 34 $this->close_pipe(IO::IN); 35 } else { 36 _print_log("proc_open failed. ".$this->_script); 37 } 38 } 39 40 function close_pipe($i) { 41 if ( isset($this->_pipes[$i]) ) { 42 fclose($this->_pipes[$i]); 43 unset($this->_pipes[$i]); 44 } 45 } 46 function get_script() { 47 return $this->_script; 48 } 49 50 function get_error() { 51 $error = stream_get_contents($this->_pipes[IO::ERR]); 52 $this->close_pipe(IO::ERR); 53 return $error; 54 } 55 56 // is still running? 57 function is_running() { 58 $status = proc_get_status($this->_resource); 59 return $status["running"]; 60 } 61 62 // long execution time, proccess is going to be killer 63 function is_over_executed() { 64 if ($this->_start_time + $this->_max_exec_time < time()) return true; 65 else return false; 66 } 67 68 function get_result() { 69 $result = stream_get_contents($this->_pipes[IO::OUT]); 70 $this->close_pipe(IO::OUT); 71 return $result; 72 } 73 74 function close() { 75 foreach ($this->_pipes as $pipe) { 76 fclose($pipe); 77 } 78 return proc_close($this->_resource); 79 } 80 }
浙公网安备 33010602011771号