使用重叠 IO 进行控制台输入? [英] Using overlapped IO for console input?

查看:23
本文介绍了使用重叠 IO 进行控制台输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用 FILE_FLAG_OVERLAPPED 标志打开 CONIN$ 来使用重叠 IO 从控制台读取输入.但是,ReadFile 在我使用时会阻塞,即使使用 OVERLAPPED 参数也是如此.

I'm attempting to use overlapped IO to read input from the console by opening CONIN$ with the FILE_FLAG_OVERLAPPED flag. However, ReadFile blocks when I use it, even with an OVERLAPPED parameter.

我读过一些帖子报告说这是一个 Windows 7 错误.我正在使用 7,所以这是可能的.

I've read some posts reporting that this is a Windows 7 bug. I am using 7 so that could be possible.

这是我正在使用的代码:

Here's the code I'm using:

// Create a console window
AllocConsole();
AttachConsole(GetProcessId(GetModuleHandle(NULL)));

HANDLE overlappedConsoleIn = CreateFile(L"CONIN$",
                              GENERIC_READ,
                              FILE_SHARE_READ,
                              NULL,
                              OPEN_EXISTING,
                              FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
                              NULL);

// Set up the console to work with stdio
FILE *consoleOut = _fdopen(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT), "w");
FILE *consoleIn = _fdopen(_open_osfhandle((long)overlappedConsoleIn, _O_TEXT), "r");

*stdout = *consoleOut;
*stdin = *consoleIn;

setvbuf(consoleOut, NULL, _IONBF, 0);
setvbuf(consoleIn, NULL, _IONBF, 0);

std::ios::sync_with_stdio();

// Create a completion event
HANDLE inputEvent = CreateEvent(NULL, true, false, NULL);

BYTE inputBuffer[128];

OVERLAPPED overlappedData;
overlappedData.Offset = 0;
overlappedData.OffsetHigh = 0;
overlappedData.hEvent = inputEvent;

DWORD numBytesRead = 0;

// Asynchronously read from console
ReadFile(overlappedConsoleIn, inputBuffer, 128, &numBytesRead, &overlappedData);

while(true)
{
    if(WaitForSingleObject(inputEvent, 0) == WAIT_OBJECT_0)
    {
        std::cout << "input has been received" << std::endl;
    }
    std::cout << "doing something" << std::endl;
}

推荐答案

当你打开 CONIN$CONOUT$ 时,参数 dwFlagsAndAttributes 是忽略(在 CreateFile 功能是关于如何打开控制台的完整说明).如果你喜欢异步读取控制台,你可以将 CreateFile 返回的句柄直接传递给 WaitForSingleObject 函数,如果有任何控制台事件未决,这个句柄将被发出信号,用函数 ReadConsoleInput 你看懂了吗?未决事件.这里是有关如何操作的完整文档在 Windows 中使用控制台.

When you open CONIN$ or CONOUT$ the parameter dwFlagsAndAttributes is ignored (in the documentation of the CreateFile function is a complete description about how to open the console). If you like to read the console asynchronously, you can pass the handle returned by CreateFile directly to the WaitForSingleObject function and if any Console event is pending this handle would be signaled, with the function ReadConsoleInput do you read the pending events. Here is the complete documentation of how to use the console in windows.

这篇关于使用重叠 IO 进行控制台输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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