【问题标题】:nonblocking read from stdin从标准输入非阻塞读取
【发布时间】:2013-02-04 04:54:06
【问题描述】:

我希望ReadConsoleW() 在读取特定数量的字节后返回。 但它不会返回。

如何让ReadConsoleW() 在完成读取指定的字节数后立即返回?

我试过的代码在这里:

#include <stdio.h>
#include <Windows.h>


int main()
{
    //something is being written to stdin.
    Sleep(2000);
    int b;
    int r;
    //read 3 wide character
    ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), &b, 3*sizeof(TCHAR), (LPDWORD)&r, NULL);
    //problem: no returns until enter pressed
    putc(b,stdout);
    while(1)
    {};
}

【问题讨论】:

    标签: c windows console nonblocking


    【解决方案1】:

    使用SetConsoleMode 关闭ENABLE_LINE_INPUT 标志。行编辑将不可用,但不会等到按下 Enter 键。

    请注意,您不能将三个WCHARs 读入int

    【讨论】:

    • 但它仍然会在缓冲区中等待至少 一个 字符...即它仍在阻止读取。
    • PeekConsoleInput 是非阻塞的,但您必须使用 ReadConsoleInput 来使用输入(或检查输入事件类型以确保 ReadConsoleChars 不会阻塞)。 (并且每当您想等待超时的控制台事件时,只需在控制台句柄上使用WaitForSingleObject)。
    【解决方案2】:

    还要考虑在 Windows 中使用 ReadFile/WriteFile 进行异步 I/O。 见MSDN on asynchronous I/O

    这有点复杂,但你确实有你想要的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2018-07-26
    • 2011-12-27
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多