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
$RETURN_CHAR = "\n";
$TIMEOUT = 5; $PID = getmypid();
$CHILD_PID = 0;
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);
}
function read_data() {
$in = fopen("php://stdin", "r");
set_timeout();
$in_string = fgets($in, 255);
clear_timeout();
fclose($in);
return $in_string;
}
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);
}
?>