非阻塞I / O在C? (视窗) [英] Non-Blocking i/o in c? (windows)

查看:109
本文介绍了非阻塞I / O在C? (视窗)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个Windows终端应用非阻塞I / O(仅适用于Windows,对不起!)。

I'm trying to get a non-blocking I/O on a Windows terminal application (windows only, sorry!).

如果我想有一个简短的输入时间在至极用户可以preSS一个按钮,但如果他不输入停止,程序继续?

What if I want to have a short input time in wich the user can press a button, but if he doesn't the input stops and the program continues?

例如:

,从1数到当用户presses某个键不管的情况下停止计时器:
我应该有一个while循环,但如果我做一个残培或getchar函数就会停止程序,对吧?

A timer that counts from 1 to whatever that stops when the user presses a certain key: I should have a while loop, but if I do a getch or a getchar function it will stop the program, right?

我知道我可以使用的kbhit(); ,但对于节目我试图让我需要知道的输入,而不是仅仅有输出!
是否有任何简单的功能,让我念想在键盘缓冲区?

I know I could use kbhit(); , but for the "program" I'm trying to make I need to know the input, not just IF THERE IS input! Are there any simple functions that would allow me to read like the last key in the keyboard buffer?

推荐答案

对于文档 _kbhit()

_kbhit 功能检查最近的按键控制台。如果函数返回一个非零值,键击正在等待缓冲。然后,程序可以调用 _getch _getche 来得到的击键。

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()说:有一些等待。这种方式也不会封锁。

So, you can still use _getch(), but limit its use to only after _kbhit() says there is something waiting. That way it won't block.

这篇关于非阻塞I / O在C? (视窗)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆