php进程间通信--有名管道

管道PIPE

  管道用于承载简称之间的通讯数据。为了方便理解,可以将管道比作文件,进程A将数据写到管道P中,然后进程B从管道P中读取数据。php提供的管道操作API与操作文件的API基本一样,除了创建管道使用posix_mkfifo函数,读写等操作均与文件操作函数相同。当然,你可以直接使用文件模拟管道,但是那样无法使用管道的特性了。

  通过管道通信的大概思路是,首先创建一个管道,然后子进程向管道中写入信息,父进程从管道中读取信息,这样就可以做到父子进程直接实现通信了。

代码如下:

<?php
//创建管道
$pipePath = "/tmp/test.pipe";
if( !file_exists( $pipePath ) ){
    if( !posix_mkfifo( $pipePath, 0666 ) ){
        exit('make pipe false!' . PHP_EOL);
    }
}

//创建进程,子进程写管道,父进程读管道
$pid = pcntl_fork();

if( $pid == 0 ){
    //子进程写管道
    $file = fopen( $pipePath, 'w' );
    fwrite( $file, 'hello world' );
    sleep(1);
    exit();
}else{
    //父进程读管道
    $file = fopen( $pipePath, 'r' );
    //stream_set_blocking( $file, False );  //设置成读取非阻塞
    echo fread( $file, 20 ) . PHP_EOL;

    pcntl_wait($status);  //回收子进程
}

下面来看一个简单的实际小例子。两个子进程向一个文件中写信息,父进程负责监听检测这个文件是否写入完成,完成之后,讲这个文件copy一份。这里,父子进程之间通过管道通信,确认是否完成写入。

<?php
//创建管道
$pipePath = "/tmp/test.pipe";
if( !file_exists( $pipePath ) ){
    if( !posix_mkfifo( $pipePath, 0666 ) ){
        exit("make pipe fail \n");
    }
}

//创建两个子进程写文件
for( $i = 0; $i < 2; $i++ ){

    $pid = pcntl_fork();
    if( $pid == 0 ){
        file_put_contents( './pipe.log', $i . " write pipe\n", FILE_APPEND );  //写入文件
        $file = fopen( $pipePath, 'w' );
        fwrite( $file, $i . "\n" );  //向管道中写标识,标识写入完毕。
        fclose( $file );
        exit();  //退出子进程
    }
}


//父进程要做的是:
//1、读取管道中的写出状态,判断是否完全写完
//2、拷贝写好的文件
//3、删除管道
//4、回收进程

$file = fopen( $pipePath, 'r' );
$line = 0;
while(1){
    $end = fread( $file, 1024 );
    foreach( str_split( $end ) as $c) {
        if ( "\n" == $c ) {
            $line++;
        }
    }

    if( $line == 2 ){
        copy( './pipe.log', './pipe_copy.log' );
        fclose( $file );
        unlink( $pipePath );
        pcntl_wait( $status );
        exit("ok \n");
    }
}
?>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值