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

查看:207
本文介绍了使用重叠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.

我已经阅读了一些报道这是W​​indows 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天全站免登陆