将数据从一个流传输到另一个流

[英]Pipe data from one stream to another


I am looking for the best way to pipe data from one stream to another without having to deal with buffering myself. Basically the equivalent of the node.js stream.pipe function.

我正在寻找将数据从一个流传输到另一个流的最佳方法,而无需自己处理缓冲。基本上相当于node.js stream.pipe函数。

There is stream_copy_to_stream, but according to the comments on the manual page it is quite a memory hog (possibly reading the whole stream into memory?).

有stream_copy_to_stream,但根据手册页上的注释,这是一个非常大的内存(可能将整个流读入内存?)。

Of course I could do something like this:

当然我可以这样做:

$fh = fopen('filename.txt', 'rb');
$out = STDOUT;
while (!feof($fh)) {
    $bytes = 1024;
    fwrite(STDOUT, fread($fh, $bytes), $bytes);
}
fclose($fh);

But I'm hoping there is an easier API to accomplish this, without having to do the buffering myself.

但我希望有一个更简单的API来完成这个,而不必自己做缓冲。

Thanks.

1 个解决方案

#1


3  

I downloaded the source code of PHP 5.4.0 and looked up stream_copy_to_stream (streams.c line 1419). It looks reasonable in my opinion.

我下载了PHP 5.4.0的源代码并查找了stream_copy_to_stream(streams.c第1419行)。在我看来,它看起来很合理。

First it tries to memory-map the source stream, and write the whole thing to the destination in one go without using an intermediate buffer.

首先,它尝试对源流进行内存映射,并在不使用中间缓冲区的情况下一次性将整个内容写入目标。

If memory mapping is not possible, then it uses an internal buffer (8192 bytes, see CHUNK_SIZE in php_streams_int.h line 49) to shuffle the data from the source to the destination.

如果无法进行内存映射,则它使用内部缓冲区(8192字节,请参阅php_streams_int.h第49行中的CHUNK_SIZE)将数据从源缓冲到目标。

Either the manual comment is wrong, or the developers have improved the function since it was first written. I would give it another look.

手动注释是错误的,或者开发人员自首次编写以来已经改进了该功能。我再试一次。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/12/31/6f2a587ecc8b0a0428f2c94ac056dd14.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com