Voting

: six plus two?
(Example: nine)

The Note You're Voting On

ben at gelbnet dot com
22 years ago
I was writing a shell script to get input from a user, however, I needed my script to time out after a certain number of seconds if the user didn't enter enough data. The code below descibes the method I used. It's a little hairy but it does work.

-Ben

#!/home/ben/php/bin/php -q
<?php
//GLOBALS
$RETURN_CHAR = "\n";
$TIMEOUT = 5; //number of seconds to timeout on input
$PID = getmypid();
$CHILD_PID = 0;

//Make sure program execution doesn't time out
set_time_limit(0);

function
set_timeout() {
global
$PID;
global
$CHILD_PID;
global
$TIMEOUT;

$CHILD_PID = pcntl_fork();
if(
$CHILD_PID == 0) {
sleep($TIMEOUT);
posix_kill($PID, SIGTERM);
exit;
}
}

function
clear_timeout() {
global
$CHILD_PID;
posix_kill($CHILD_PID, SIGTERM);
}

// read_data()
// gets a line of data from STDIN and returns it
function read_data() {

$in = fopen("php://stdin", "r");
set_timeout();
$in_string = fgets($in, 255);
clear_timeout();
fclose($in);
return
$in_string;
}

// write_data($outstring)
// writes data to STDOUT
function write_data($outstring) {
$out = fopen("php://stdout", "w");
fwrite($out, $outstring);
fclose($out);
}

while(
1) {
write_data("say something->");
$input = read_data();
write_data($RETURN_CHAR.$input);
}

?>

<< Back to user notes page

To Top