set_time_limit is not affecting PHP-CLI

The solution here is to use pcntl_fork(). I'm afraid it's POSIX only. PHP will need to be compiled with --enable-pcntl and not --disable-posix. Your code should look something like this:

<?php

function done($signo)
{
    // You can do any on-success clean-up here.
    die('Success!');
}

$pid = pcntl_fork();
if (-1 == $pid) {
    die('Failed! Unable to fork.');
} elseif ($pid > 0) {
    pcntl_signal(SIGALRM, 'done');
    sleep($timeout);
    posix_kill($pid, SIGKILL);
    // You can do any on-failure clean-up here.
    die('Failed! Process timed out and was killed.');
} else {
    // You can perform whatever time-limited operation you want here.
    exec($cmd);
    posix_kill(posix_getppid(), SIGALRM);
}

?>

Basically what this does is fork a new process which runs the else { ... } block. At the (successful) conclusion of that we send an alarm back to the parent process, which is running the elseif ($pid > 0) { ... } block. That block has a registered signal handler for the alarm signal (the done() callback) which terminates successfully. Until that is received, the parent process sleeps. When the timeout sleep() is complete, it sends a SIGKILL to the (presumably hung) child process.


I'm ssuming that the script hangs in a loop somewhoere. Why not simply do a $STARTUP_TIME=time() the the script start, and then keep checking in the loop if the script neeeds to exit?


Could you try running your php via exec and use the "timeout" command? (http://packages.ubuntu.com/lucid/timeout)

usage: timeout [-signal] time command.


The max_execution_time limit, which is what set_time_limit sets, counts (at least, on Linux) the time that is spent by the PHP process, while working.

Quoting the manual's page of set_time_limit() :

Note: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself.
Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running.
This is not true on Windows where the measured time is real.

When, you are using sleep(), your PHP script is not working : it's just waiting... So the 5 seconds you are waiting are not being taken into account by the max_execution_time limit.

Tags:

Php