Home > Article > Backend Development > Set timeout limit for function in pcntl_alarm in php_PHP tutorial
The principle is to set a clock signal before the function is executed. If the execution of the function exceeds the specified time, the signal will be triggered, and the signal processing function (sig) will throw an exception and be caught by the outer code. This will jump out of the execution of the original function, and then execute the following code. If the function is within the specified time, the clock signal will not be triggered. The clock signal will be cleared after the function ends, and no exception will be thrown
Go to PHP official to view the description of this function
pcntl_alarm (PHP 4 >= 4.3.0, PHP 5)
pcntl_alarm — Set an alarm clock signal for the process
Description¶int pcntl_alarm (int $seconds)
Create a timer that sends a SIGALRM signal to the process after a specified number of seconds. Each call to pcntl_alarm() cancels the previously set alarm signal.
Parameter ¶seconds The number of seconds to wait. If seconds is set to 0, the alarm signal will not be created.
Return Value¶ Returns the number of seconds remaining before the last alarm schedule (before the alarm signal is sent), or returns 0 if there is no previous alarm schedule (Translation: or the previous schedule has been completed).
Example
The code is as follows
|
Copy code
|
||||
declare(ticks = 1);
function a() { Sleep(10);echo "a finishin"; }function b() {
} function c() |
{
function sig()
} catch(Exception $e) {The code is as follows | Copy code |
# cd /usr/local/src/php -5.2.6/ext/pcntl #phpize # ./configure --with-php-config=/usr/local/php/bin/php-config # make && make install pcntl.so Add to php.ini OK http://www.bkjia.com/PHPjc/632645.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632645.htmlTechArticleThe principle is to set a clock signal before the function is executed. If the execution of the function exceeds the specified time, the signal will be Triggered, the signal processing function (sig) will throw an exception, which is generated by the outer layer... |