Devrim Devrim - 3 years ago 139
PHP Question

set_time_limit is not affecting PHP-CLI

How to solve set_time_limit not affecting PHP-CLI?

#!/usr/bin/php -q
sleep(5); // actually, exec() call that takes > 2 seconds
echo "it didn't work again";

Answer Source

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:


function done($signo)
    // You can do any on-success clean-up here.

$pid = pcntl_fork();
if (-1 == $pid) {
    die('Failed! Unable to fork.');
} elseif ($pid > 0) {
    pcntl_signal(SIGALRM, 'done');
    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.
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download