Win32 - read from stdin with timeout

前端 未结 6 1441
时光取名叫无心
时光取名叫无心 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:16

    In case anyone is writing chrome native messaging host and is looking for solution to check if there is any input on stdin without blocking then this works perfect:

    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
    int timer = GetTickCount();
    while(timer+10000 > GetTickCount())
    {
        unsigned int length = 0;
        DWORD bytesAvailable = 0; 
        PeekNamedPipe(hStdin,NULL,0,NULL,&bytesAvailable,NULL);
        if(bytesAvailable > 0)
        {
            for (int i = 0; i < 4; i++)
            {
                unsigned int read_char = getchar();
                length = length | (read_char << i*8);
            }
    
    
            for (int i = 0; i < length; i++)
            {
                msg += getchar();
            }
            timer = GetTickCount();
        }
        else
        {
            // nothing to read, stdin empty
            Sleep(10);
        }
    }
    

提交回复
热议问题