首页 > 解决方案 > ncurses 带有信号的 getch() 行为

问题描述

我的代码设置了一个计时器,它每 x 秒发送一次 SIG_ALRM。然后它进入一个调用 getch() 的输入处理循环。

    int total_keys = 0;
    while (1) {
        inputchar = wgetch(mywindow);
        mvprintw(LINES - 2, 2, "%d", total_keys++);
        refresh();
        switch (inputchar) {
            ...
        }
    }

由于我将 getch() 设置为阻塞 ( wtimeout(mywindow, -1);),因此我希望 total_keys 仅在我按下一个键时才会上升,但我发现每次收到 SIG_ALRM 时,getch() 都会返回并且 total_keys 会增加。有谁知道为什么会这样?

编辑:这是我的 SIG_ALRM 处理程序

void alarm_handler(int signum, siginfo_t *si, void *ucontext) {
    timer_t *timeridp = si->si_value.sival_ptr;
    if (*timeridp == *update_timerp) {
        update();
    }
}

标签: cncurses

解决方案


检查是否有错误返回,发生这种情况时不要处理输入。

while (1) {
    inputchar = wgetch(mywindow);
    if (inputchar == ERR) {
        if (errno == EINTR) {
            continue;
        } else {
            // report failure somehow
        }
    }
    mvprintw(LINES - 2, 2, "%d", ++total_keys);
    refresh();
    switch (inputchar) {
        ...
    }
}

推荐阅读