上一篇文章讲到了php进程通信的进程信号通信方法,本文介绍的是有名管道:
管道通信,主要是利用文件,写入以及读取来进行通信的,
通俗来讲,就是A进程在1.txt写入1,B进程读取1.txt,就能读取到这个1,这样就通信成功了.
当然,php进程管道通信没有这么简单
注意:多进程系列文章,都建立在linux环境,php-cli运行模式下
一:创建个专属管道的文件:
$fifoPath = "tmp/$name".getmypid() ;
if (!file_exists($fifoPath)) {
if (!posix_mkfifo($fifoPath, 0666)) {
return false;
}
} else {
return false;
}
复制
二:读取数据
$r_pipe = fopen($fifoPath, 'r');
if ($r_pipe == NULL) {
return false;
}
$data = fread($r_pipe, 1024);
复制
三:写入数据
$w_pipe = fopen($fifoPath, 'w');
if ($w_pipe == NULL) {
throw new Exception('打开管道错误!');
}
$result = fwrite($w_pipe, $data);
复制
四:删除管道
五:封装类
<?php
class Pipe
{
public $fifoPath;
private $w_pipe;
private $r_pipe;
function __construct($name = 'pipe', $mode = 0666)
{
$fifoPath = "tmp/$name".getmypid() ;
if (!file_exists($fifoPath)) {
if (!posix_mkfifo($fifoPath, $mode)) {
return false;
}
} else {
return false;
}
$this->fifoPath = $fifoPath;
}
function open_write()
{
$this->w_pipe = fopen($this->fifoPath, 'w');
if ($this->w_pipe == NULL) {
throw new Exception('打开管道错误!');
}
return true;
}
function write($data)
{
return fwrite($this->w_pipe, $data);
}
function write_all($data)
{
$w_pipe = fopen($this->fifoPath, 'w');
fwrite($w_pipe, $data);
fclose($w_pipe);
}
function close_write()
{
return fclose($this->w_pipe);
}
function open_read()
{
$this->r_pipe = fopen($this->fifoPath, 'r');
if ($this->r_pipe == NULL) {
return false;
}
return true;
}
function read($byte = 1024)
{
return fread($this->r_pipe, $byte);
}
function read_all()
{
$r_pipe = fopen($this->fifoPath, 'r');
$data = '';
while (!feof($r_pipe)) {
$data .= fread($r_pipe, 1024);
}
fclose($r_pipe);
return $data;
}
function close_read()
{
return fclose($this->r_pipe);
}
function rm_pipe()
{
return unlink($this->fifoPath);
}
}
复制
六:注意事项
1:管道与普通文件有一点非常不同的就是:管道需要先有个进程读取进程,才可以写入,否则按写入模式打开文件时阻塞,以下是测试截图:
评论(0)