栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

PHP CLI:如何从TTY中读取输入的单个字符(无需等待回车键)?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP CLI:如何从TTY中读取输入的单个字符(无需等待回车键)?

我的解决方案是

-icanon
在TTY上设置模式(使用
stty
)。例如。:

stty -icanon

因此,现在可以使用的代码是:

#!/usr/bin/php<?phpsystem("stty -icanon");echo "input# ";while ($c = fread(STDIN, 1)) {    echo "Read from STDIN: " . $c . "ninput# ";}?>

输出:

input# fRead from STDIN: finput# oRead from STDIN: oinput# oRead from STDIN: oinput# Read from STDIN:input#

完成操作后,别忘了还原TTY …

恢复tty配置

通过在更改终端状态之前保存tty状态,可以将终端重置回原来的状态。完成后,您可以恢复到该状态。

例如:

<?php// Save existing tty configuration$term = `stty -g`;// Make lots of drastic changes to the ttysystem("stty raw opost -ocrnl onlcr -onocr -onlret icrnl -inlcr -echo isig intr undef");// Reset the tty back to the original configurationsystem("stty '" . $term . "'");?>

这是保存tty并将其放回用户开始之前的方式的唯一方法。

请注意,如果您不担心保留原始状态,只需执行以下操作即可将其重置回默认的“健全”配置:

<?php// Make lots of drastic changes to the ttysystem("stty raw opost -ocrnl onlcr -onocr -onlret icrnl -inlcr -echo isig intr undef");// Reset the tty back to sane defaultssystem("stty sane");?>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/466122.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号