开发者

Does PHP's fread() always read at least 4096 bytes?

According to Drupal 7's bootstrap file:

// PHP only performs buffered reads, so in reality it will always read
// at least 4096 bytes. Thus, it costs nothing extra to read and store
// much so as t开发者_Go百科o speed any additional invocations.

PHP will always read 4096 no matter if you specified a lower value for the length parameter. Is this true? If so, is there really no way to do unbuffered reads?

Edit: I'd like to read /dev/urandom without consuming entropy unnecessarily.


If you have a file of less than 4096 bytes then it would be less, or padded with null values I'd imagine.

What's wrong with a 4096 byte long buffer anyway - it's too small to affect memory consumption in any major way, unless there's something I'm missing here.


Here I got a function for you in PHP - stream_set_read_buffer():

int stream_set_read_buffer ( resource $stream , int $buffer )

buffer : The number of bytes to buffer. If buffer is 0 then read operations are unbuffered. This ensures that all reads with fread() are completed before other processes are allowed to write to that output stream.

So, if you want to change the default behavior then this function should be useful to experiment.


A possible work-around for PHP < 5.3 would seem to be to use file_get_contents():

$output = file_get_contents('/dev/urandom', FALSE, NULL, -1, $bytes);

The invocation is a little ugly. Not sure how to confirm it's unbuffered, however, other than reading the C source.

http://svn.php.net/viewvc/php/php-src/branches/PHP_5_2/ext/standard/file.c?revision=298881&view=markup

http://svn.php.net/viewvc/php/php-src/branches/PHP_5_2/main/streams/streams.c?revision=293175&view=markup

It doesn't look like the input stream is flagged to be unbuffered, so it seems this also reads at least the minimum buffer size out of it on PHP 5.2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜