amazon web services - Impose time limit to popen/fgets in PHP


I want impose a time limit to a process reading using fgets opened by popen in PHP.

I have the next code:

$handle = popen("tail -F -n 30 /tmp/pushlog.txt 2>&1", "r");
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "data: ".$buffer."\n";

I tried without success:


The process is as follow:

  1. The browser send a GET request waiting for a Answer in HTML5 Server side events format.
  2. The request is received by AWS Load Balancer and is forwarded to EC2 instances.
  3. The answer is the last 30 lines of the file
  4. The browser receive it in 30 messages and the connection is persisted.
  5. If tail command sends a new line it is returned else fgets wait undefined time until new line is returned from tail command.
  6. AWS Load Balancer after 60 seconds of network inactivity (No new lines in 60 seconds) closes the connection to the browser. The connection to EC2 instance is not closed.
  7. The browser detect that the connection is closed and it opens a new connection, the process go back to step 1.

AS this steps describe, the connection between AWS Load Balancer and EC2 instance is never closed, after a few hours/days there is hundreds and hundreds of tail and httpd process running and the server start not answering.

Of course it appear to be a AWS Load Balancer bug, but I don't want start a process to gain the attention from Amazon and wait for a fix.

My temporary solution is do a sudo kill tail to kill the process before the server becomes unstable.

I think PHP doesn't stop the script because PHP is "blocked" waiting for fgets to finish.

I know that the time limit of AWS Load Balancer is editable, but I want keep in the default value, even a higher limit is not going to fix the problem.

I don't know if I need change the question to How to execute a process in linux with a time limit / timeout?.

PHP 5.5.22 / Apache 2.4 / Linux Kernel 3.14.35-28.38.amzn1.x86_64




Tested with PHP 5.5.20:

//Change configuration.

//Open pipe & set non-blocking mode.
$descriptors  = array(0 => array('file', '/dev/null', 'r'),
                      1 => array('pipe', 'w'),
                      2 => array('file', '/dev/null', 'w'));
$process      = proc_open('exec tail -F -n 30 /tmp/pushlog.txt 2>&1',
                                $descriptors, $pipes, NULL, NULL) or exit;
$stream       = $pipes[1];
stream_set_blocking($stream, 0);

//Call stream_select with a 10 second timeout.
$read = array($stream); $write = NULL; $except = NULL;
while (!feof($stream) && !connection_aborted()
        && stream_select($read, $write, $except, 10)) {

    //Print out all the lines we can.
    while (($buffer = fgets($stream)) !== FALSE) {
        echo 'data: ' . $buffer . "\n";


//Clean up.
$status = proc_get_status($process);
if ($status !== FALSE && $status['running'] === TRUE)



Rather than using a process file pointer, I went with my "multitasking" approach. I use this code to spawn other "processes" Kind of a multitasking cheat.

I call a Script, hang.php, that just hangs for 90 seconds:sleep(90).

You may want to adjust the stream and stream_select timeouts.

Create stream(s)

header('Content-Type: text/plain; charset=utf-8');
$timeout = 20; 
$result = array(); 
$sockets = array(); 
$buffer_size = 8192;
$id = 0;
$stream = stream_socket_client("", $errno,$errstr, $timeout,
if ($stream) {
  $sockets[$id++] = $stream;  // supports multiple sockets
  $http = "GET /testbed/hang.php HTTP/1.0\r\nHost:\r\n\r\n"; 
  fwrite($stream, $http);
else { 
  echo "$id Failed\n";

Additional scripts can be run by adding the stream:$sockets[$id++] = $stream;

Below will put anything read in to the$result[$id] array.

Monitor the streams:

while (count($sockets)) {
  $read = $sockets; 
  stream_select($read, $write = NULL, $except = NULL, $timeout); 
  if (count($read)) {
    foreach ($read as $r) { 
      $id = array_search($r, $sockets); 
      $data = fread($r, $buffer_size); 
      if (strlen($data) == 0) { // either reads data or EOF
        echo "$id Closed: " . date('h:i:s') . "\n\n\n";
      else {
        $result[$id] .= $data; 
  else { 
    echo 'Timeout: ' . date('h:i:s') . "\n\n\n";
echo system('ps auxww');


When I want to kill a process I usesystem('ps auxww') to get the pid and kill it withsystem("kill $pid")


header('Content-Type: text/plain; charset=utf-8');
//system('kill 220613');

echo system('ps auxww');

People are also looking for solutions to the problem: curl - Allow access to protected file through PHP


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.