在PHP CLI中对STDIN进行非阻塞

Pet*_*tah 14 php stdin

无论如何都要读取STDIN非阻塞的PHP:

我试过这个:

stream_set_blocking(STDIN, false);
echo fread(STDIN, 1);
Run Code Online (Sandbox Code Playgroud)

还有这个:

$stdin = fopen('php://stdin', 'r');
stream_set_blocking($stdin, false);
echo 'Press enter to force run command...' . PHP_EOL;
echo fread($stdin, 1);
Run Code Online (Sandbox Code Playgroud)

但它仍会阻塞,直到fread得到一些数据.

我注意到一些关于这个(7岁)的开放式错误报告,所以如果无法完成,是否有人知道任何可以实现此目的的粗暴黑客(在Windows和Linux上)?

Mar*_*tin 12

这就是我能想到的.它在Linux中工作正常,但在Windows上,只要我按下一个键,输入就会被缓冲,直到按下enter键.我目前正在尝试找到一种方法来禁用流上的缓冲,或者特别是在PHP中的STDIN上.

<?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
    }
}

?>
Run Code Online (Sandbox Code Playgroud)


Ser*_* NN 5

只是一个通知,非阻塞 STDIN 现在正在工作。