c - c中的非阻塞i/o? ( window )

标签 c io nonblocking

我正在尝试在 Windows 终端应用程序(仅限 Windows,抱歉!)上获得非阻塞 I/O。

如果我想要一个很短的输入时间,用户可以按下一个按钮,但如果他没有按下按钮,输入就会停止,程序会继续运行怎么办?

例如:

一个计时器,从 1 开始计数,直到用户按下某个键时停止: 我应该有一个 while 循环,但如果我执行 getch 或 getchar 函数,它会停止程序,对吗?

我知道我可以使用 kbhit(); ,但对于我试图制作的“程序”,我需要知道输入,而不仅仅是如果有输入! 是否有任何简单的函数可以让我像键盘缓冲区中的最后一个键一样阅读?

最佳答案

来自documentation for _kbhit() :

The _kbhit function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.

所以,在你的循环中:

while (true) {
    // ...
    if (_kbhit()) {
        char c = _getch();
        // act on character c in whatever way you want
    }
}

因此,您仍然可以使用 _getch(),但将其使用限制在 _kbhit() 表示有等待的情况下。这样它就不会阻塞。

关于c - c中的非阻塞i/o? ( window ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294713/

相关文章:

c++ - 指向静态变量的指针和指向某个变量的静态指针之间的区别

java - Spring Boot 2 的非阻塞 IO

c++ - WinSocks 的非阻塞 connect()

javascript - Node.js:识别脚本是异步的还是非阻塞的

c - At&T Assembly 索引数组和声明数组

c - 有没有办法在预处理条件中使用 sizeof ?

While 循环参数内的逗号

C 文件 I/O 问题

c - I/O - C 字符串的操作

c++ - cppreference.com 上的 IO 错误表 (C++)