对于多进程之间的通信,研究了一天管道,封装了一个管道类,一个处理多进程的类。pipeline的理论稍后补充,代码先补充。path=$path;返回$这个;}}if(posix_mkfifo($path,$mode)){$this->path=$path;返回$这个;}else{$this->throwException('创建管道失败');}}/***抛出异常方法*/publicfunctionthrowException($msg='failed'){thrownew\Exception($msg);}/***设置阻塞方式**@parambool$blockfalse是非阻塞的,true是阻塞的*/publicfunctionsetBlock($block=false){$this->block=$block;}/***指定管道文件路径*/publicfunctionsetPath($path){if(!file_exists($path)){$msg=$path.'管道不存在';$this->throwException($msg);}$this->path=$path;}/***获取管道文件路径*/publicfunctiongetPath(){return$this->path;}/***打开一个管道**@paramstring$modeopentype*/publicfunctionpipeOpen($mode='r'){$handler=fopen($this->path,$mode);if(!is_resource($handler)){$msg='openpipe'.$this->path.'失败的';$this->throwException($msg);}//设置阻塞类型stream_set_blocking($handler,$this->block);$this->handler=$handler;返回$这个;}/***打开管道进行读取**@returnre来源*/publicfunctionreadOpen(){return$this->pipeOpen('r');}/***以书面方式打开管道**@returnresource*/publicfunctionwriteOpen(){return$this->pipeOpen('w');}/***读取一行,或给定的长度*/publicfunctionreadOne($byte=1024){$data=fread($this->handler,$byte);返回$数据;}/***读取所有内容*/publicfunctionreadAll(){$hd=$this->handler;$数据='';while(!feof($hd)){$data.=fread($hd,1024);}返回$数据;}/***写入数据*/publicfunctionwrite($data){$hd=$this->handler;尝试{fwrite($hd,$data);}catch(\Exception$e){$this->throwException($e->getMessage());}返回$this;}/***关闭管道*/publicfunctionclose(){returnfclose($this->handler);}/***删除管道*/publicfunctionremove(){returnunlink($this->path);}}多进程处理类,使用管道保存各个进程的返回结果,主进程处理最终结果//子进程受保护$child=[];//子进程pid数组受保护$result=[];//计算结果publicfunction__construct($process=[]){$this->process=$process;}/***设置子进程*/publicfunctionsetProcess($process){$this->process=$process;}/***forkchildprocess*/publicfunctionforkProcess(){$process=$this->process;foreach($processas$k=>$item){$pid=pcntl_fork();如果($pid==0){$pipe=newfifoPipeClass();$id=getmypid();$pipe->writeOpen();$pipe->write($k.'pid:'.$id.PHP_EOL);$管道->关闭();出口(0);}elseif($pid>0){$this->child[]=$pid;}}返回$this;}/***等待子进程结束*/publicfunctionwaiteProcess(){$child=$this->child;$pipe=newfifoPipeClass();$pipe->readOpen();echo'全部开始'.PHP_EOL;while(count($child)){foreach($childas$k=>$pid){$res=pcntl_waitpid($pid,$status,WNOHANG);如果(-1==$res||$res>0){unset($child[$k]);$data=$pipe->readOne();如果($data){$this->result[]=$data;}}$pipe->close();echo'全部结束'.PHP_EOL;$管道->删除();返回$这个;}/***获取返回结果*/publicfunctiongetResult(){return$this->result;}}$obj=newpipeMultiProcess();$obj->setProcess(['姓名'=>1,'年龄'=>2,'性别'=>3]);$res=$obj->forkProcess()->waitProcess()->getResult();print_r($res);结果如下:Array([0]=>agepid:7436[1]=>sexpid:7437namepid:7435)
