PHP写一个大文件 - 缓存的RAM

I'm experiencing a problem that is driving me crazy and I can't understand why it is happening.

My System is Ubuntu 14.04 with 16GB Ram.

I have a PHP Script with the following Code

<?php
$fp = fopen( "http://...", 'r' );

$write_pointer = fopen( 'test.bin', 'a' );
while ( !feof( $fp ) )
{
    fwrite( $write_pointer, stream_get_line( $fp, 4096 ) );
    fflush( $write_pointer );
}
fclose( $write_pointer );
fclose( $fp );
?>

It reads from HTTP (endless) and writes to a file. This file can be a very big one, as much as 40 GB since it's endless.

I'm writing the file (test.bin) in the Disk, not in a RAM-Disk or something.

The problem is that the CACHED RAM is being increased all the time, and after 1-2 days it goes 100% only in CACHED.

Can someone explain to me why this is happening? Why is it consuming so much RAM?

And even when I clear the Buffers, after 1-2 days the same thing will happen

Thank you Regards

You can bypass the issue by tracking the time duration your $write_pointer has been open, and closing/re-opening after a certain time period.

Because of the nature of Linux kernel that caches files into RAM. In a healty Linux system free memory is always near 0 and cache is near the non-used memory. You can clear cache periodically with this command:

sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

Pay attention that despite a lot of sources state cache memory is immediately freed when a process reclaims it, in some circumstances when memory is heaviliy used cached memory could lead to out of memory crashes, and it's not a Linux bug, it's more a bad design. If your swap is not been used then you don't have to worry about free memory. Don't confuse buffers with caches. Buffers are used while writing, caches for reading.