I'm very confused at the moment.
我现在很困惑。
What I want to do is create a listener function, that wait for two commands - and the thing is it should only listen every two hundred milliseconds and ignore the other input from the user.
我要做的是创建一个侦听器函数,它等待两个命令——问题是它应该每200毫秒监听一次,忽略用户的其他输入。
function foo() {
read -sN1 _input
case "${_input}" in
A) echo 'Option A';;
B) echo 'Option B';;
esac
}
while true; do
sleep 0.2
foo
done
If I "hammer" the A-key (or UP-key) ten times, it writes "Option A" ten times (although, slowly) - when it should only had time to write it at most three times. Why is that - and how do I fix it?
如果我“敲击”A-key(或上键)十次,它会写“选项A”十次(虽然,很慢)——而它最多只能写三次。为什么会这样,我该怎么修复呢?
3 个解决方案
#1
3
Your terminal buffers the input to your program. In order to make your program ignore the input it received while it sleeps, you should clear the input buffer before calling read
. To my knowledge there is not way to do this in bash.
终端将输入缓存在程序中。为了使程序忽略它在休眠时接收到的输入,您应该在调用read之前清除输入缓冲区。据我所知,在bash中没有办法做到这一点。
#2
0
You can put your sleep function within a block where stdin is closed:
你可以将你的睡眠功能放在stdin关闭的区域内:
{
sleep 0.2
} <&-
Alternatively, you can clear (read and discard) the stdin buffer right after the sleep:
或者,您可以在睡眠后清除(读取和丢弃)stdin缓冲区:
sleep 0.2
read -t 1 -n 10000 discard
#3
0
This is what I came up with that worked. It isn't very nice, but it works.
这就是我想出的办法。这不是很好,但是很有效。
function inputCommand() {
_now=`date +%s%N | cut -b1-13`
_time=$(($_now-$_timeout))
if [ $_time -gt 500 ]; then
$1
_timeout=`date +%s%N | cut -b1-13`
fi
}
function keyPressUp() {
echo "Key Press Up"
}
function waitForInput() {
unset _input
read -sN1 _input
case "${_input}" in
A) inputCommand "keyPressUp";;
esac
}
while true; do
waitForInput
done
#1
3
Your terminal buffers the input to your program. In order to make your program ignore the input it received while it sleeps, you should clear the input buffer before calling read
. To my knowledge there is not way to do this in bash.
终端将输入缓存在程序中。为了使程序忽略它在休眠时接收到的输入,您应该在调用read之前清除输入缓冲区。据我所知,在bash中没有办法做到这一点。
#2
0
You can put your sleep function within a block where stdin is closed:
你可以将你的睡眠功能放在stdin关闭的区域内:
{
sleep 0.2
} <&-
Alternatively, you can clear (read and discard) the stdin buffer right after the sleep:
或者,您可以在睡眠后清除(读取和丢弃)stdin缓冲区:
sleep 0.2
read -t 1 -n 10000 discard
#3
0
This is what I came up with that worked. It isn't very nice, but it works.
这就是我想出的办法。这不是很好,但是很有效。
function inputCommand() {
_now=`date +%s%N | cut -b1-13`
_time=$(($_now-$_timeout))
if [ $_time -gt 500 ]; then
$1
_timeout=`date +%s%N | cut -b1-13`
fi
}
function keyPressUp() {
echo "Key Press Up"
}
function waitForInput() {
unset _input
read -sN1 _input
case "${_input}" in
A) inputCommand "keyPressUp";;
esac
}
while true; do
waitForInput
done