How can we prevent a function from being executed for too long? In PHP, the pcntl clock signal + exception can be used for implementation.
How can we prevent a function from being executed for too long? In PHP, the pcntl clock signal + exception can be used for implementation.
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.