set_time_limit is not affecting PHP-CLI

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

How to solve set_time_limit not affecting PHP-CLI?

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


        
6条回答
  •  旧时难觅i
    2020-12-30 06:45

    EDIT 1

    I noticed this comment in PHP manual:

    Please note that, under Linux, sleeping time is ignored, but under Windows, it counts as execution time.

    As far as what I understand, sleep is implemented as a system call and therefore ignored by PHP as described in the manual.

    EDIT 2

    there is an exec() running instead of sleep() there. and some exec() stuff hangs indefinitely. i am also searching for killing it from within exec (on linux shell), like exec(kill_after15secs myscript.sh), but i can't seem to find that either

    I now see the actual question. Assuming that you're working in a Lunix/Unix environment, you can devise a solution around these lines:

    test-out.txt 2>&1 & echo $!' ); ?>
    

    Guess what, this captured the process id of the process you started. You can log it into a database or text file along with timestamp. In another cron script that runs, say, every 5 minutes, retrieve all process ids that were created 5 minutes ago and check if they are still running:

    
    

    If process is still running, you get two lines of output:

     PID TTY STAT TIME COMMAND
    2044 ?   S    0:29 sh test.sh
    

    If so, terminate it like this:

    
    

    I wrote an article about creating background processes in PHP (and hunt them down afterwards). All examples were copied from there.

    EDIT 3

    All dots connected together:

    test-out.txt 2>&1 & echo $!' );
        $timer = 300;
        while( --$timer ) {
            sleep(1);
            $status = system( 'ps ' . $pid );
            $status = explode( "\n", $status, 2 ); // I am not sure, please experiment a bit here
            if ( count( $status ) == 1 || trim( $status[ 1 ] ) == '' ) {
                die( 'spawned process ended successfully' );
            }
        }
        system( 'kill ' . $pid );
        die( 'spawned process was terminated' );
    ?>
    

提交回复
热议问题