How can I determine if there is an input waiting for stdin on windows?

I want to determine if there is an expected input value for stdin on Windows.

I use the following general structure on Linux:

fd_set currentSocketSet;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
int result = 1;
while (result > 0){
    FD_ZERO(&currentSocketSet);
    FD_SET(STDIN, &currentSocketSet);
    result = select(STDIN+1, &currentSocketSet, NULL, NULL, &tv);
    if (result == -1){
        printf("Network Error -- select errored with id=%d.\n", errno);
        return;
    } else if (result > 0){
        //...do stuff
    }
}

Note. I don't want to deal with keyboard and keyboard functions like kbhit. I want to do what I asked. I also don’t want the third-party library to do this either, I would like the call from the Windows library to trigger an answer.

Note # 2: In the windows, the code above is with error code Windows 10038 "The operation was attempted for something that is not a socket", which probably means that the windows do not support STDIN selection.

+4
source share
3 answers

, Linux!= Windows, "select()" .

, Windows . .

... ...

API Win32, :

',

PS:

, . GetStdHandle (STD_INPUT_HANDLE), .

+1

As already stated, on Windows you should use GetStdHandle(), and the return handle cannot be mixed with sockets. But, fortunately, the returned handle can be tested using WaitForSingleObject(), like many other handles in Windows. There, you can do something like this:

#include <stdio.h>
#include <windows.h>

BOOL key_was_pressed(void)
{
    return (WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE),0)==WAIT_OBJECT_0);
}

void wait_for_key_press(void)
{
    WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE),INFINITE);
}

int main()
{
    if(key_was_pressed())
        printf("Someone pressed a key beforehand\n");

    printf("Wait until a key is pressed\n");

    wait_for_key_press();

    if(key_was_pressed())
        printf("Someone pressed a key\n");
    else
        printf("That can't be happening to me\n");

    return 0;
}

EDIT: Forgot to say you need to read the characters from the descriptor so key_was_pressed () returns FALSE.

+1
source

Source: https://habr.com/ru/post/1537155/


All Articles