RedBullet
RedBullet

Reputation: 531

How to have web page stop long running process

I have the following code, which runs a process that runs forever (until killed) and display the results (using tail -F below just as an illustration):

<?php
$cmd = "tail -F /var/log/whatever.log";
set_time_limit(0);

$handle = popen($cmd, "r");

if (ob_get_level() == 0)
    ob_start();

while(!feof($handle)) {

    $buffer = fgets($handle);
    echo $buffer . "<br />";
    ob_flush();
    flush();
    sleep(1);
}

pclose($handle);
ob_end_flush();
?>

This sort of works, my process runs, but it continues to run when I stop loading page, close tab, etc.

Is there some mechanism I can take advantage of to stop the process when I am not showing the page? I'm sure there is, but not clear.

Upvotes: 3

Views: 106

Answers (1)

Ruben Kazumov
Ruben Kazumov

Reputation: 3892

...
header("Content-type:text/html");// start the content serving
echo("\n"); // connection with the browser
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo $buffer . "<br />";
    ob_flush();
    flush();
    sleep(1);
    if (connection_status()!=0){ // check the connection
        die; // or whatever you want to stop the work 
    }
}

...

Upvotes: 1

Related Questions