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.
In the Unix world this would be simple with select()
but that doesn't work in Windows because stdin
isn't a socket. What's the next simplest option without creating extra threads etc?
I'm using visual C++ targeting a Win32 environment.
so far I have tried:
using
select
(doesn't work if the input is not a socket)using
WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE))
. - Remy's first suggestion. This always seems to return immediately when you call it if the standard input is a console (others have reported the same problem)using overlapped IO and doing a
WaitForSingleObject
(Remy's third suggestion). In this case the read always seems to block when the input is coming from a console - it seems thatstdin
does not support asynchronous I/O.
At the moment I'm thinking my only remaining option is to create a thread which will do a blocking read and then signal an event, and then have another thread which waits for the event with a timeout.
See Question&Answers more detail:os