views:

82

answers:

2

Hi,

I want to stop a while true loop when a specific or any key is pressed.

I know I can ctrl-c the script but I am locking tables in my MySql database, and I doesn't want to unlock them in the beginning of the script because i want to be able to run multiple instance of the script.

Thank you for any insight

+1  A: 

You may want to check the ncurse extension. Not documented but ncurses_getch should be what you're looking for.

Arkh
+1  A: 

Ctrl+C sends SIGINT which by default terminates an application or script immediately. If you build a catch for that, you can have your script end more cleanly.

<?php
declare(ticks = 1);

pcntl_signal(SIGTERM, "sig_handle");
pcntl_signal(SIGINT, "sig_handle");
$TERMINATE = false;

function sig_handle($signal)
{
    switch($signal)
    {
        case SIGTERM:
            print "Got SIGTERM\n";
            $TERMINATE = true;
        break;
        case SIGKILL:
            print "Got SIGKILL\n";
            $TERMINATE = true;
        break;
        case SIGINT:
            print "User pressed Ctrl+C - Got SIGINT\n";
            $TERMINATE = true;
        break;
    }
}


while(true)
{
     // Do everything and anything - though infinite loops, not the best idea.
     if( $TERMINATE )
     {
            // Perform all cleaning functions.
            // Then break the loop
            break 2;
     }
}

// Just because Ctl+C was passed it only broke the loop, you can add other hooks into your program to help capture this break and more quickly terminate your script.
?>
Marco Ceppi