note 109604 modified in function.popen by danbrown

From: Date: Fri, 10 Aug 2012 16:22:24 +0000
Subject: note 109604 modified in function.popen by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190021@lists.php.net to get a copy of this message
fread is blocking on streams from popen.

That means that if you do 

<?php
 $stream = popen("tail -f myfile");
 fread($stream, 100);
?>

then fread will only return full chunks of 100 characters. So if the size of myfile isn't a multiple of 100, the last chunk will not be returned.

This is documented in https://bugs.php.net/bug.php?id=51056 . Some people in that bug discussion argue that this should be kept to not change behaviour, but example #3 on http://php.net/fread clearly says "When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available."

A workaround is to call 

 <?php stream_set_blocking($stream, 0); ?>

on the stream you get from popen(). --was-- fread is blocking on streams from popen. That means that if you do $stream = popen("tail -f myfile"); fread($stream, 100); then fread will only return full chunks of 100 characters. So if the size of myfile isn't a multiple of 100, the last chunk will not be returned. This is documented in https://bugs.php.net/bug.php?id=51056 . Some people in that bug discussion argue that this should be kept to not change behaviour, but example #3 on http://dk.php.net/fread clearly says "When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available." A workaround is to call stream_set_blocking($stream, 0); on the stream you get from popen(). http://php.net/manual/en/function.popen.php

« previous php.notes (#190021) next »