How to solve set_time_limit not affecting PHP-CLI?
#!/usr/bin/php -q
2 second
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:
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.