Skip to main content

set_time_limit is not effecting PHP-CLI



any solution to this ?







#!/usr/bin/php -q

<?php

set_time_limit(2);

sleep(5); // actually, exec() call that takes > 2 seconds

echo "it didn't work again";







Source: Tips4all

Comments

  1. 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:

    <?php

    function done($signo)
    {
    // You can do any on-success clean-up here.
    die('Success!');
    }

    $pid = pcntl_fork();
    if (-1 == $pid) {
    die('Failed! Unable to fork.');
    } elseif ($pid > 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.

    ReplyDelete
  2. The max_execution_time limit, which is what set_time_limit sets, counts (at least, on Linux) the time that is spent by the PHP process, while working.

    Quoting the manual's page of set_time_limit() :


    Note: The set_time_limit() function and the configuration
    directive max_execution_time only
    affect the execution time of the
    script itself. Any time spent on
    activity that happens outside the
    execution of the script such as system
    calls using system(), stream
    operations, database queries, etc. is
    not included when determining the
    maximum time that the script has been
    running. This is not true on
    Windows where the measured time is
    real.


    When, you are using sleep(), your PHP script is not working : it's just waiting... So the 5 seconds you are waiting are not being taken into account by the max_execution_time limit.

    ReplyDelete
  3. Could you try running your php via exec and use the "timeout" command? (http://packages.ubuntu.com/lucid/timeout)

    usage: timeout [-signal] time command.

    ReplyDelete
  4. I'm ssuming that the script hangs in a loop somewhoere. Why not simply do a $STARTUP_TIME=time() the the script start, and then keep checking in the loop if the script neeeds to exit?

    ReplyDelete
  5. Very hackish, but since I use cli scripts a lot, I admit shamefully to having slapped up a similar hack in the past. 2 scripts needed.

    Your first cron script (the one that hangs) logs its starttime and processid in a flat file -> the function getmypid will be your friend for this. A second script run from cron every (x) minutes checks the flatfile, kills whatever has passed the alloted execution time, clears the flatfile and even logs in another file if you want.

    Good luck ;)

    UPDATE:

    Remembered this question and came back to post this. While rummaging through Sebastian Bergmann's github account I stumbled on php-invoker. In the words of the author:



    Utility class for invoking PHP callables with a timeout.



    Although the current answer is very good for linux based non portable use, if cross-platform solution is needed this solution should be windows compatible, for those poor souls running on windoze. Mr Bergmann being a PHP god, I totally vouch for the quality of the script.

    ReplyDelete
  6. 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:

    <?php $pid = system( 'sh test.sh >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:

    <?php $status = system( 'ps ' . $pid ); ?>


    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:

    <?php system( 'kill ' . $pid ); ?>


    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:

    <?php
    $pid = system( 'sh test.sh >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' );
    ?>

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex