Non-blocking on STDIN in PHP CLI

后端 未结 4 877
死守一世寂寞
死守一世寂寞 2020-12-14 10:07

Is there anyway to read from STDIN with PHP that is non blocking:

I tried this:

stream_set_blocking(STDIN, false);
echo fread(STDIN, 1);         


        
相关标签:
4条回答
  • 2020-12-14 10:29

    Just a notice, that non blocking STDIN working, now.

    0 讨论(0)
  • 2020-12-14 10:31

    Petah, I can't help with the PHP side of this directly, but I can refer you to an article I ran across a while ago in which someone emulated transistors by testing within a shell script for the existence of pending data for a named pipe. It's a fascinating read, and takes shell scripting to a whole new level of geekiness. :-)

    The article is here: http://www.linusakesson.net/programming/pipelogic/

    So ... in answer to your "crude hacks" request, I suppose you could shunt your stdio through named pipes, then exec() the tool whose source is included at the URL above to test whether anything is waiting to be sent through the pipe. You'd probably want to develop some wrapper functions to help with stuff.

    I suspect the pipelogic solution is Linux-only, or at least would require a unix-like operating system. No idea how this could be accomplished on Windows.

    0 讨论(0)
  • 2020-12-14 10:33
    system('stty cbreak');
    while(true){
        if($char = fread(STDIN, 1)) {
            echo chr(8) . mb_strtoupper($char);
        }
    }
    
    0 讨论(0)
  • 2020-12-14 10:43

    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
        }
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题