How to read available input without blocking on Windows

天涯浪子 提交于 2019-12-11 23:06:14

问题


On Linux, I can read available input without blocking the process:

fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK )
char buf[n];
int r = fread(buf, 1, n, stdin);
if (r == 0){
    printf("nothing\n");
}
else {
    printf("read: ");
    fwrite(buf, 1, r, stdout);
    printf("\n");
}

The input origin can be anything, such as a file, a terminal or a pipe.

How can I do it on Windows XP?

Thanks.


回答1:


Why not read the input from a second thread? Depending on your situation, it might be a much easier approach, instead of using non-blocking IO's.




回答2:


You can achieve this on Windows by passing FILE_FLAG_OVERLAPPED to CreateFile(). It doesn't quite look the same as Linux and there may be some slight differences but it achieves the same thing.

Take a look at the MSDN page on Synchronous vs. Asynchronous IO which provides you with even more detail on the various options.



来源:https://stackoverflow.com/questions/3643738/how-to-read-available-input-without-blocking-on-windows

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