Non-blocking on STDIN in PHP CLI
Just a notice, that non blocking STDIN working, now.
Here's what I could come up with. It works fine in Linux, but on Windows, as soon as I hit a key, the input is buffered until enter is pressed. I don't know a way to disable buffering on a stream.
<?php
function non_block_read($fd, &$data) {
$read = array($fd);
$write = array();
$except = array();
$result = stream_select($read, $write, $except, 0);
if($result === false) throw new Exception('stream_select failed');
if($result === 0) return false;
$data = stream_get_line($fd, 1);
return true;
}
while(1) {
$x = "";
if(non_block_read(STDIN, $x)) {
echo "Input: " . $x . "\n";
// handle your input here
} else {
echo ".";
// perform your processing here
}
}
?>
system('stty cbreak');
while(true){
if($char = fread(STDIN, 1)) {
echo chr(8) . mb_strtoupper($char);
}
}