我的解决方案是设置-icanon
TTY 上的模式(使用stty
). Eg.:
stty -icanon
所以,现在有效的代码是:
#!/usr/bin/php
<?php
system("stty -icanon");
echo "input# ";
while ($c = fread(STDIN, 1)) {
echo "Read from STDIN: " . $c . "\ninput# ";
}
?>
Output:
input# fRead from STDIN: f
input# oRead from STDIN: o
input# oRead from STDIN: o
input#
Read from STDIN:
input#
支持此处给出的答案:
有没有办法等待并从(远程)终端会话中按下按键? https://stackoverflow.com/questions/3315538/is-there-a-way-to-wait-for-and-get-a-key-press-from-a-remote-terminal-session/3315627#3315627
有关更多信息,请参阅:
http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html#AEN92 http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html#AEN92
完成后不要忘记恢复 TTY...
恢复 tty 配置
在进行更改之前,可以通过保存 tty 状态来将终端重置回原来的状态。完成后您可以恢复到该状态。
例如:
<?php
// Save existing tty configuration
$term = `stty -g`;
// Make lots of drastic changes to the tty
system("stty raw opost -ocrnl onlcr -onocr -onlret icrnl -inlcr -echo isig intr undef");
// Reset the tty back to the original configuration
system("stty '" . $term . "'");
?>
这是保留 tty 并将其恢复为用户开始之前的状态的唯一方法。
请注意,如果您不担心保留原始状态,则只需执行以下操作即可将其重置回默认的“正常”配置:
<?php
// Make lots of drastic changes to the tty
system("stty raw opost -ocrnl onlcr -onocr -onlret icrnl -inlcr -echo isig intr undef");
// Reset the tty back to sane defaults
system("stty sane");
?>