Bash Read -t 但以毫秒为单位?

问题描述 投票:0回答:1

嗨,在我的代码中,我有 while 循环,在 while 循环的开始,我使用 read 函数来创建终止函数。 因此,每次程序执行循环时,它都会首先检查您是否按下了终止按钮。

问题是,读命令超时时间不能短于1秒。这使得程序慢得令人恼火。

有没有办法让读取命令以毫秒为单位超时? 或者我应该用其他东西来终止该程序?

while(true)

do
 read -n1 -t 0.01 killer
 if [ "$killer" == "k" ]
 then
   echo "ill!!!"
   pkill -9 -e -f gnome-terminal- # a ros node that's running in the background
   pkill -9 -e -f Test_PI.sh # the name of the bash
 fi

 echo "working"
 clear
done
bash timeout
1个回答
-1
投票

根据 Bash 变更日志,bash-4.0-alpha 引入了分数超时:

y。 内置的

-t
选项现在支持分数超时 价值观。

来源:read



这可以通过以下方式轻松测试:

Bash Changelog

使用它,您可以将脚本更改为:

$ time read -t 0.4 real 0m0.400s user 0m0.000s sys 0m0.000s

或者如果您利用零超时,您可以这样做

while :; do if read -n1 -t 0.01 key; then if [[ "$key" == "k" ]]; then ... fi fi done



while :; do if read -t 0 && read -n1 key; then if [[ "$key" == "k" ]]; then ... fi fi done ::

如果在超时秒内未读取完整的输入行,则导致 
-t timeout 超时并返回失败。
read 可以是小数点后带有小数部分的十进制数。
 仅当 
timeout
正在从终端、管道或其他特殊文件读取输入时,此选项才有效;从常规文件读取时它没有效果。 如果
read
为 0,则如果指定文件描述符上的输入可用,则 read 返回成功,否则返回失败。 如果超时则退出状态大于128。

来源:timeout,第

man bash
部分

    

© www.soinside.com 2019 - 2024. All rights reserved.