Win32 - read from stdin with timeout

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

    Use GetStdHandle() to get the stdin handle. You can then either:

    1. use WaitForSingleObject() i the stdin handle itself to detect when there is console input available for reading, then read from it as needed.

    2. use GetNumberOfConsoleInputEvents() or PeekConsoleInput() on the stdin handle in a loop to determine when there is data available for reading, then read from it as needed.

    3. use ReadFile() with an OVERLAPPED structure containing an event handle, then use the event handle with WaitForSingleObject() to detect if the read times out.

    In any case, be careful if stdin has been redirected. If it is redirected to something than is not console I/O, you can't use a GetStdHandle() handle with console functions. If it is redirected to a file, you have to use ReadFile().

提交回复
热议问题