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

时间:2018-07-03 08:57:48

标签: bash timeout

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

问题是读取命令超时不能短于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

1 个答案:

答案 0 :(得分:0)

您不正确,read可以处理小数超时。

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

所以我将您的脚本更改为

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

或者如果您使用零超时,则可以

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

  

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

     

来源:man bash,第read部分