Set timeout for PHP function execution. How can we prevent a function from being executed for too long? In PHP, you can use pcntl clock signals + exceptions. The code is as follows: declare (ticks1); functiona () {sleep (10); how does echoafinishi prevent a function from taking too long to execute? In PHP, you can use pcntl clock signals + exceptions.
The code is as follows:
declare(ticks = 1); function a(){ sleep(10); echo "a finishi\n";}function b(){ echo "Stop\n";}function c(){ usleep(100000);}function sig(){ throw new Exception;}try{ pcntl_alarm(1); pcntl_signal(SIGALRM, "sig"); a(); pcntl_alarm(0);}catch(Exception $e){ echo "timeout\n";}b();a();b();
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 is triggered, and the signal processing function throws an exception and is 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.
Why? In PHP, you can use pcntl clock signals + exceptions. The code is as follows: declare (ticks = 1); function a () {sleep (10); echo "a finishi \...