views:

274

answers:

2

Hi, I was just wondering whether in C is it possible to peek in the input buffer or perform similar trickery to know whether a call to fgets would block at a later time. Java allows to do something like that by calling BufferedReader.ready(), this way I can implement console input something like this:

while (on && in.ready()) { 
  line = in.readLine();
  /* do something with line */
  if (!in.ready())
    Thread.sleep(100);
}

this allows an external thread to gracefully shutdown the input loop by setting on to false; I'd like to perform a similar implementation in C without resorting to non portable tricks, I already know I can make a "timed out fgets" under unix by resorting to signals or (better, even though requering to take care of buffering) reimplement it on top of recv/select, but I'd prefer something that would work on windows too.

TIA

+1  A: 

Suggest to go with socket I/O routines,preferably poll() with required millisecond as timeout and eventually you can interpret timeout ( return value = -1 ) as unavailability of data in input buffer.
In my opinion,there is no non-blocking standard I/O function to achieve this functionality.

A: 

I'm not certain what are you talking about: a socket or a file handle?

For files there should be no blocking. The function returns immediately (besides of the I/O invocation itself).

For sockets - you may use the ioctlsocket function: The following tells if there's a rcv data pending:

ULONG nSize;
ioctlsocket(sock, FIONREAD, &nSize);

The following transfers the socket into non-blocking mode:

ULONG nEnable = 1;
ioctlsocket(sock, FIONBIO, &nEnable);

When in Non-blocking mode - functions on socket never block. If they can't fulfill the request they return an error, and the error code is WSAEWOULDBLOCK

Plus, on Windows there're dozens of much more efficient methods. Those are:

  • Using Overlapped I/O. This is non-trivial, but gives superior performance
  • Associating socket with a waitable event. This transfers the socket to a non-blocking mode, plus the specified event is signaled when a network event occurs.
  • Associate it with the window handle. This is convenient for UI-oriented programs.
valdo