set_time_limit is not affecting PHP-CLI

前端 未结 6 895
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 05:52

How to solve set_time_limit not affecting PHP-CLI?

#!/usr/bin/php -q 
 2 second         


        
6条回答
  •  我在风中等你
    2020-12-30 06:38

    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.

提交回复
热议问题