October 22, 2024
Chicago 12, Melborne City, USA
C#

Win32 – read from stdin with timeout


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:

  1. using select (doesn’t work if the input is not a socket)

  2. 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)

  3. 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 that stdin 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.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video