【问题标题】:how to use non-blocking way to check stdin is empty or not如何使用非阻塞方式检查标准输入是否为空
【发布时间】:2021-11-22 09:27:52
【问题描述】:

我想读取键盘操作,有些键会生成ESC[...,当我读取ESC时,我想判断是ESC键按下还是其他键。 (就是我读的时候,怎么查看stdin缓冲区里有没有字符?)

我关闭了行输入模式,在linux下我可以用下面的代码解决问题:

int check_keydown()
{
#if defined _WIN32

#else
     int ch = 0;
     int res = read(STDIN_FILENO, &ch, 1);
     if (res > 0)return ch;
     return -1;
#endif
}

但是我不知道如何在windows中实现同样的功能。

(我查看了ncurses的源代码,它使用ReadConsoleInput来读取键盘操作,这不是我想要的。我想知道如何检查stdin缓冲区是否为空 非阻塞方式)

谁能告诉我该怎么做,提前谢谢。

【问题讨论】:

  • 你最好使用ncurses这样的库
  • @EugeneSh。 (其实我问这个问题是因为没打算用)
  • 由于 ncurses 是开源的,您可以查看源代码并了解它是如何完成的。我确定您需要调用一些特定于 Windows 的函数。
  • 我不会依赖 Linux 中的这种方法。终端设备有点古怪,但一般来说,来自未配置为非阻塞模式的文件的read()ing 实际上会阻塞,直到至少可以传输一个字节或遇到错误或 EOF。
  • @thebusybee 听起来不错,我搜索了一段时间,但没有找到。

标签: c windows terminal


【解决方案1】:

对于非阻塞 IO,您可以在 stdin 上使用 pollselect

#include <stdio.h> // stdin
#include <poll.h> // int poll(struct pollfd *fds, nfds_t nfds, int timeout);

struct pollfd fd;
fd.fd = stdin;
fd.events = POLLIN; // "There is data to read."
fd.revents = 0;
int ret = poll(&fd, 1, 0);
if (ret > 0 && (fd.revents & POLLIN != 0))  {
  // got some data
}
else {
  perror("poll failed on stdin");
}

【讨论】:

  • emmm,我希望它在 Windows 上工作
  • 我的错,我误会了。使用 mingw 或 cygwin 是一种选择吗?我相信它会让你使用你当前的 POSIX 代码。
  • 听起来不错,但我决定使用PeekConsoleInputReadConsoleInput
猜你喜欢
  • 2011-12-27
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 2019-11-15
  • 1970-01-01
相关资源
最近更新 更多