Win32 - read from stdin with timeout

前端 未结 6 1448
时光取名叫无心
时光取名叫无心 2020-12-06 10:11

I\'m trying to do something which I think should be simple: do a blocking read from standard input, but timing out after a specified interval if no data is available.

<
6条回答
  •  醉酒成梦
    2020-12-06 11:04

    This should do it:

    int main()
    {
        static HANDLE stdinHandle;
        // Get the IO handles
        // getc(stdin);
        stdinHandle = GetStdHandle(STD_INPUT_HANDLE);
    
        while( 1 )
        {
            switch( WaitForSingleObject( stdinHandle, 1000 ) )
            {
            case( WAIT_TIMEOUT ):
                cerr << "timeout" << endl;
                break; // return from this function to allow thread to terminate
            case( WAIT_OBJECT_0 ):
                if( _kbhit() ) // _kbhit() always returns immediately
                {
                    int i = _getch();
                    cerr << "key: " << i << endl;
                }
                else // some sort of other events , we need to clear it from the queue
                {
                    // clear events
                    INPUT_RECORD r[512];
                    DWORD read;
                    ReadConsoleInput( stdinHandle, r, 512, &read );
                    cerr << "mouse event" << endl;
                }
                break;
            case( WAIT_FAILED ):
                cerr << "WAIT_FAILED" << endl;
                break;
            case( WAIT_ABANDONED ): 
                cerr << "WAIT_ABANDONED" << endl;
                break;
            default:
                cerr << "Someting's unexpected was returned.";
            }
        }
    
        return 0;
    }
    

提交回复
热议问题