How to read available input without blocking on Wi

2019-09-11 21:20发布

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.

2条回答
戒情不戒烟
2楼-- · 2019-09-11 21:55

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.

查看更多
你好瞎i
3楼-- · 2019-09-11 22:01

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.

查看更多
登录 后发表回答