The principle is to set a clock signal before the function is executed. if the function is executed more than the specified time, the signal is triggered. the signal processing function (sig) throws an exception and is captured by the outer code.
The principle is to set a clock signal before the function is executed. if the function execution exceeds the specified time, the signal will be triggered, and the signal processing function (sig) will throw an exception, captured by the outer code. In this way, the execution of the original function is jumped out, and the following code is executed. If the function does not trigger the clock signal within the specified time period, and the clock signal is cleared after the function ends, no exception is thrown.
Go to the php official website to view this function description
Pcntl_alarm (PHP 4> = 4.3.0, PHP 5)
Pcntl_alarm-set an alarm signal for the process
Description: optional int pcntl_alarm (int $ seconds)
Create a timer and send a SIGALRM signal to the process after the specified number of seconds. Each call to pcntl_alarm () cancels the previously set alarm signal.
The number of seconds that the ¶ seconds parameter is waiting. If seconds is set to 0, the alarm signal is not created.
Return value: the number of seconds remaining for the last alarm scheduling (sent from the alarm signal), or 0 if no alarm scheduling is available or the previous scheduling is completed.
The instance code is as follows:
-
- Declare (ticks = 1 );
- Function ()
- {
- Sleep (10 );
- Echo "a finishin ";
- }
- Function B ()
- {
- Echo "Stopn ";
- }
- Function c ()
- {
- Usleep (100000 );
- }
-
- Function sig ()
- {
- Throw new Exception;
- }
-
- Try
- {
- // Set an alarm signal to be executed once per second
- Pcntl_alarm (1 );
- // Install the alarm signal and bind the callback
- Pcntl_signal (SIGALRM, "sig ");
- A ();
- // Cancel the alarm signal
- Pcntl_alarm (0 );
- }
- Catch (Exception $ e)
- {
- Echo "timeoutn ";
- }
- B ();
- A ();
- B ();
Appendix: pcntl extension installation
The pcntl extension can support php multi-thread operations. the configrue prompt added -- enable-pcntl after PHP needs to be re-compiled. the code is as follows:
- # Cd/usr/local/src/php-5.2.6/ext/pcntl
- # Phpize
- #./Configure -- with-php-config =/usr/local/php/bin/php-config
- # Make & make install
Add pcntl. so to php. ini. OK