2

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.

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?

4

3 回答 3

3

您的终端缓冲程序的输入。为了让你的程序忽略它在睡眠时收到的输入,你应该在调用之前清除输入缓冲区read。据我所知,在 bash 中没有办法做到这一点。

于 2012-08-17T13:24:26.950 回答
0

您可以将睡眠功能放在标准输入关闭的块中:

  {
    sleep 0.2
  } <&- 

或者,您可以在睡眠后立即清除(读取和丢弃)标准输入缓冲区:

sleep 0.2
read -t 1 -n 10000 discard
于 2012-08-17T13:27:24.090 回答
0

这就是我想出的有效方法。这不是很好,但它有效。

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
于 2012-08-17T13:42:31.147 回答