首页 > 解决方案 > 使用输入管道和管理键盘

问题描述

我尝试运行一个通过传入管道读取流的 PHP 脚本,并且我也想管理键盘:cat /etc/passwd|./readSlow.php 该脚本将从管道中读取每个字符并在标准输出上缓慢显示,直到用户按“q”键(不按 RETURN)。实际上,脚本读取管道并缓慢显示文本。但是当我按下'q'时它并没有停止(它会显示它,我需要在'q'之后按RETURN键才能激活停止)。

#!/usr/bin/php
<?php
// ReadSlow

// This tool take a file in input and read it, character by caracter to the
// output.
// It add a sleep time between each character.

// Wait 0.2s between each char
$defaultSpeed = 0.5;

if (($input = fopen ("php://stdin", "r")) === false)
  die ("Can not open stdin\n");
if (($keyboard = fopen("/dev/tty", "r")) === false)
  die ("Can not open /dev/tty\n");
stream_set_blocking($keyboard, false);

$speed = $defaultSpeed;

while (($char = fgetc ($input)) !== false)
{
  if (($key = fgetc ($keyboard)) === "q") // get input from keyboard
    break;
  usleep ($speed * 1000000);
  echo "$char";
}
 
fclose ($input);

最后,我希望有更多可用的密钥。

问题:我应该如何混合标准输入和键盘中的管道(不显示按下的键,不等待返回键)?

我尝试玩“stty”,但每次,我都有“stty:'标准输入':设备不合适的 ioctl”

我在 Linux 上,如果它改变了一些东西,我会使用 Bash。

谢谢

标签: pipekeyboardphpstdin

解决方案


问题是 stdin 和 tty 是同一个输入通道。如果您无需管道就可以逃脱,请通过“ ./readSlow.php /etc/passwd ”尝试以下代码。这会将要打印的文件作为命令行参数。命令“stty -echo”禁止按下按键的输出。

    #!/usr/bin/php
    <?php
    // ReadSlow
    
    // This tool take a file in input and read it, character by caracter to the
    // output.
    // It add a sleep time between each character.
    
    // Wait 0.2s between each char
    $defaultSpeed = 0.5;
    
    if (($input = fopen ($argv[1], "r")) === false)
      die ("Can not open $argv[1]\n");
    if (($keyboard = fopen("/dev/tty", "r")) === false)
      die ("Can not open /dev/tty\n");
    stream_set_blocking($keyboard, false);
    
    system("stty -echo");
    
    $speed = $defaultSpeed;
    
    while (($char = fgetc ($input)) !== false)
    {
      if (($key = fgetc ($keyboard)) === "q") // get input from keyboard
        break;
      usleep ($speed * 1000000);
      echo "$char";
    }
    
    fclose ($input);
    echo "\n";
    system("stty echo");

推荐阅读