PHP多进程编程(四) 用php实现管道通信类
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP多进程编程(四) 用php实现管道通信类,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2414字,纯文字阅读大概需要4分钟。
内容图文
![PHP多进程编程(四) 用php实现管道通信类](/upload/InfoBanner/zyjiaocheng/931/11fd242a0a2e44b1ae638664e7799a46.jpg)
实现代码如下:
<?php
class Pipe
{
public $fifoPath;
private $w_pipe;
private $r_pipe;
/**
* 自动创建一个管道
*
* @param string $name 管道名字
* @param int $mode 管道的权限,默认任何用户组可以读写
*/
function __construct($name = 'pipe', $mode = 0666)
{
$fifoPath = "/tmp/$name." . posix_getpid();
if (!file_exists($fifoPath)) {
if (!posix_mkfifo($fifoPath, $mode)) {
error("create new pipe ($name) error.");
return false;
}
} else {
error( "pipe ($name) has exit.");
return false;
}
$this->fifoPath = $fifoPath;
}
///////////////////////////////////////////////////
// 写管道函数开始
///////////////////////////////////////////////////
function open_write()
{
$this->w_pipe = fopen($this->fifoPath, 'w');
if ($this->w_pipe == NULL) {
error("open pipe {$this->fifoPath} for write error.");
return false;
}
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) {
error("open pipe {$this->fifoPath} for read error.");
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)) {
//echo "read one K\n";
$data .= fread($r_pipe, 1024);
}
fclose($r_pipe);
return $data;
}
function close_read()
{
return fclose($this->r_pipe);
}
////////////////////////////////////////////////////
/**
* 删除管道
*
* @return boolean is success
*/
function rm_pipe()
{
return unlink($this->fifoPath);
}
}
?>
有了这个类,就可以实现简单的管道通信了,因为这个教程是多进程编程系列教程的一个部分。
这个管道类的应用部分,将放到下一节。
内容总结
以上是互联网集市为您收集整理的PHP多进程编程(四) 用php实现管道通信类全部内容,希望文章能够帮你解决PHP多进程编程(四) 用php实现管道通信类所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。