Meetings every second Tuesday
PHP CLI Memory Issues
I've googled and now I'm turning to the local PHP'ers for help.
I've written a PHP CLI application that runs as a constant background process on our Unix server. The problem I get is, as the application does its job, it slowly builds up memory and never releases it. Eventually it hits the memory_limit I've specified in the ini and fails. I've used the unset() function on my objects once they are not needed and then the app goes to sleep for 30 seconds. However, the memory is never released. I am STUMPED! I could really use some help.
Here is an example of a small script that builds up the memory and then tries to free it up; it doesn't work:
<code>#!/usr/local/bin/php -c /usr/local/etc/php-cli.ini
<?PHP
class TestObj{
private $testArr;
public function __construct(){}
public function __destruct(){}
public function testme(){
$this->testArr = array();
for($i = 0; $i < 100000; $i++){
$something = "";
for($j = 0; $j < 10; $j++){
$something .= chr(rand(35,126) );
}
$this->testArr[$i] = $something;
}
}
}
echo "Initial Memory Usage: ".memory_get_usage()."\n\n";
sleep(10);
echo "Creating New Object\n\n";
$test = new TestObj();
echo "Running Test Function\n\n";
$test->testme();
echo "Ready to destroy object in...";
for($x=5 ; $x > 0; $x--){
sleep(1);
echo $x, "...";
}
unset($test);
echo "\nSleepy Time\n";
//Goto Sleep so we can monitor the memory
sleep(30);
?>
</code>




There was a bug a year ago
There was a bug a year ago that seemed similar to your code in PHP 5.05 and earlier. See this:
http://bugs.php.net/bug.php?id=32596
What version are you running under? An update may be in order.
Also, from what I've learned so far, PHP doesn't free-up used memory (especially any that might have leaked memory) until the PHP interpreter shuts down so I don't know how well it will work as a background service/daemon.
Does anyone out there have any experience running a PHP script as a service? I've done some CLI scripts but I've never tried to make it run non-stop. Regular CRON execution has always worked for the kinds of apps I was building.
Thanks.
Stradius, Thanks for the
Stradius,
Thanks for the reply. I'm using PHP 5.1.6. I could use it via cron but then I'm afraid of overlap with existing processes. I never know how much processing is going to be done at any time and I don't want to start another process if there is an existing process. I'm afraid because of the heavy mysql inserts that it would create conflicts. I'm good with mysql but not a guru. Maybe this isn't even an issue and maybe someone can offer a suggestion. For clarification here is my system setup:
Any solution found ?
I've got a similar problem (PHP5.2.1 under Linux) where my script doesn't work non-stop but does a few thousand times some kind of replace on a file (personnalized mailing).
In the end, did you find a solution ?