Non-Blocking i/o in c? (windows)

我的未来我决定 提交于 2019-12-08 00:57:20

问题


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

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?

For example:

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?

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?


回答1:


From the 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.

So, in your loop:

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

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.



来源:https://stackoverflow.com/questions/21294713/non-blocking-i-o-in-c-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!