Gforth 中的非阻塞输入

wol*_*ats 1 time forth keyboard-events gforth

如果我们使用 ncurses 进行一个非常简单的计数器:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ncurses.h>

int main(void) {
  struct timespec start;
  clock_gettime(CLOCK_REALTIME, &start);
  initscr();
  cbreak();
  nodelay(stdscr, TRUE);
  {
    int key = -1;
    struct timespec delay, now;
    do {
      clock_gettime(CLOCK_REALTIME, &delay);
      delay.tv_sec = 0;
      delay.tv_nsec = 1000L * 1000L * 1000L - delay.tv_nsec;
      nanosleep(&delay, NULL);
      clock_gettime(CLOCK_REALTIME, &now);
      mvprintw(1, 1, "%ld\n", (long)(now.tv_sec - start.tv_sec));
      refresh();
      key = getch();
      if (key >= 0)
        break;
    } while (now.tv_sec - start.tv_sec < 60);
  }
  endwin();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

按任意键后它会中止(好吧,因为cbreak()使用ctrl-C总是可以工作,无需任何额外的努力......)。

但我们可以让它变得更复杂,比如添加一个函数来暂停计数器或即时重置它(+/- 1 秒)。

为此,我们肯定需要一个非阻塞的键盘输入。

我想知道在 Gforth 中是否可以做到这一点?好的,我知道如何捕获像 SIGINT 这样的中断,但是像上面那样,适用于任何键或任何预定的键?

fiz*_*fiz 5

使用key?,它会返回一个标志,如果新输入可用,则该标志为 true。

您可以根据需要扩充以下代码,但我认为它解释了循环运行直到按下按键的基本思想。

: run-until-key ( -- )
    0
    begin
        \ place your terminal code here
        ." Num:" dup . cr
        1+
    key? until drop ;
Run Code Online (Sandbox Code Playgroud)

如果你想等待某个特定的键,只需在until前面添加一个if即可:

...
key? if key 13 = else false then until
...
Run Code Online (Sandbox Code Playgroud)

您还可以在那里添加计时器。