管道
管道是比较常用的多进程通信手段,管道分为无名管道与有名管道,无名管道只能用于具有亲缘关系的进程间通信,而有名管道可以用于同一主机上任意进程。
理解
为了方便理解,可以将管道比作文件,进程A将数据写到管道P中,然后进程B从管道P中读取数据。php提供的管道操作API与操作文件的API基本一样,除了创建管道使用posix_mkfifo函数,读写等操作均与文件操作函数相同。当然,你可以直接使用文件模拟管道,但是那样无法使用管道的特性了。
代码
// 定义管道路径,与创建管道
$pipe_path = './test.pipe';
if(!file_exists($pipe_path)){
if(!posix_mkfifo($pipe_path,0664)){
exit("create pipe error!");
}
}
$pid = pcntl_fork();
if($pid == 0){
// 子进程,向管道写数据
$file = fopen($pipe_path,'w');
while (true){
fwrite($file,'hello world');
$rand = rand(1,3);
sleep($rand);
}
exit("child end!\n");
}else{
// 父进程,从管道读数据
$file = fopen($pipe_path,'r');
while (true){
$rel = fread($file,11);
echo "{$rel}\n";
$rand = rand(1,2);
sleep($rand);
}
}
运行结果
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。