揮発性のメモ2

http://d.hatena.ne.jp/iww/

標準入力のタイムアウトつき読み込み

#!/usr/bin/php -q
<?
//  $fh = fsockopen( "172.16.101.10", 9000, $errno, $errstr, 5 );
    $fh = fopen( "php://stdin", "rb" ) or die("fopen");
    
    stream_set_timeout( $fh, 3 );
    while( $buf = fread($fh,256) ){
        print( "buf='$buf'\n" );
    }
?>

標準入力が相手では、stream_set_timeout()は機能しない! *1
selectを使って地味に待つしか無い

#!/usr/bin/php -q
<?
//  $fh = fsockopen( "172.16.101.10", 9000, $errno, $errstr, 5 );
    $fh = fopen( "php://stdin", "rb" ) or die("fopen");
    
    while( $buf=fread_timeout($fh,256,3) ){
        print( "buf='$buf'\n" );
    }


    // ★タイムアウト付きfread
    function fread_timeout( $handle, $length, $seconds=0 )
    {
        stream_set_blocking( $handle, 0 );
        $contents = "";
        $left = $length;
        
        while( $left>0 && ftimeout( $handle, $seconds ) ){
            if( ! $buf=fread($handle,$left) ) break;
            $contents .= $buf;
            $left = $length-strlen($contents);
        }
        return $contents;
    }
    // ★データが来るまで待つ
    function ftimeout( $handle, $seconds )
    {
        return stream_select( $r=array($handle), $w=null, $e=null, $seconds );
    }
?>

*1:普通のネットワークソケットなら普通に機能する