在PHP CLI中对STDIN进行非阻塞 [英] Non-blocking on STDIN in PHP CLI

查看:162
本文介绍了在PHP CLI中对STDIN进行非阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,都可以使用非阻塞的PHP从STDIN进行读取:

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

我尝试过:

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

和这个:

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

,但是它仍然会阻塞,直到fread获得一些数据为止.

but it still blocks until fread gets some data.

我注意到了一些有关此问题的公开错误报告(已有7年之久了),因此,如果无法做到这一点,是否有人知道(在Windows和Linux上)能做到这一点的粗暴黑客?

I noticed a few open bug reports about this (7 years old), so if it can't be done, does any one know any crude hacks that could accomplish this (on Windows and Linux)?

  • https://bugs.php.net/bug.php?id=34972
  • https://bugs.php.net/bug.php?id=47893
  • https://bugs.php.net/bug.php?id=48684

推荐答案

这就是我能想到的.它在Linux上可以正常工作,但是在Windows上,只要我按下一个键,输入就会被缓冲,直到按下Enter.我不知道一种禁用流缓冲的方法.

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

?>

这篇关于在PHP CLI中对STDIN进行非阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆