P
P
PO6OT2015-09-24 20:29:53
PHP
PO6OT, 2015-09-24 20:29:53

How to avoid stopping a self-invoking script?

The script calls itself with ping(), forming an infinite loop, so bypassing runtime limits:
But sometimes the script stops working. Probably the ping () request does not reach or the next script dies while waiting for an exclusive block.
Here is the first option:

daemon.php

<?php
if(date('His')-file_get_contents('./date')<3)
    exit;
    file_put_contents('./date', date('His'));
    $f=fopen('./lock', 'w+');
    flock($f, LOCK_EX);
function ping($action){
    $h=$_SERVER[HTTP_HOST];
    $http=fsockopen($h, 80, $e1, $e2, 1);
if($http){
    fwrite($http,
    'GET /'.$action.' HTTP/1.1'."\r\n".
    'Accept: */*'."\r\n".
    'Host: '.$h."\r\n\r\n"
    );
    fclose($http);
}
}
    ping('core.php');
    sleep(3);
    ping('daemon.php');
    usleep(200);
    flock($f, LOCK_UN);

This script runs for about 5 minutes, causing a Resource Limit Exceeded error on average 1 time/minute.
Here is the second, improved version:
daemon.php

<?php
if(date('His')-file_get_contents('./date')<3)
    exit;
    $f=fopen('./lock', "w+");
    flock($f, LOCK_EX);
    file_put_contents('./date', date('His'));
    include('./lib.inc');
    ping('core.php');
    sleep(3);
    flock($f, LOCK_UN);
    usleep(200);
    ping('daemon.php');
    sleep(2);
if(flock($f, LOCK_EX|LOCK_NB)){
    flock($f, LOCK_UN);
    sleep(15);
    ping('daemon.php');
}

This script runs for about 30 minutes, causing a Resource Limit Exceeded error on average 1 time/15 minutes.
Why does the script stop working and how to fix it?
Attempts to avoid stopping:
Tried:
If you try to ping('daemon.php') recursively until you find that the /lock file is locked, i.e. the next process starts, then there is a heavy load on the server and frequent 508 errors. In this case, the script runs for no more than 5 minutes.
If you try to call ping('daemon.php') twice at intervals, the script runs for 30 minutes.
Haven't tried it:
You could try having two or more servers calling each other every 5 minutes (time to experiment with).
Attempts to minimize the occurrence of 508 errors (minor):
Haven't tried it:
You can try to remove exclusive locks and leave only the last run date control as protection against double launch - if(date('His')-file_get_contents('./date')<3). I assume that the protection will not survive and the server will be loaded with simultaneous launches.
You can use a semaphore instead of locks. I guess the best option.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kim, 2015-09-24
@kimono

Looks like it's running out of allocated memory. See php.ini and measure memory usage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question