Gforth 中的非阻塞输入

Non-blocking input in 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;
}

它在按下任意键后中止(好吧,因为 cbreak() 使用 ctrl-C 总是可以在没有任何额外的努力...)。

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

为此,我们绝对需要非阻塞键盘输入。

我想知道是否可以在 Gforth 中执行此操作?好的,我知道如何在那里捕获像 SIGINT 这样的中断,但是像上面那样,为 any 键或 any 预定键工作?

使用 key?,它 returns a flag 如果新输入可用,则为真。

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

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

如果你想等待一个特定的键,只需要在until之前添加一个if:

...
key? if key 13 = else false then until
...

您也可以在此处添加计时器。