Check if fgets is blocking

I'm just wondering if it is possible in C to look into the input buffer or perform a similar trick to find out if the fgets call will block later. Java allows you to do something like this by calling BufferedReader.ready (), so I can implement console input of something like this:

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

this allows the external thread to gracefully disable the input loop by setting the value to false; I would like to perform a similar implementation in C without resorting to intolerable tricks, I already know that I can do a “fouts timeout” under Unix, resorting to signals or (better, even if requested to take care of buffering) override it on top recv / select, but I would prefer something that works on windows too.

TIA

+3
source share
2 answers

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

+1
source

I'm not sure what you're talking about: socket or file descriptor?

There should be no lock for files. The function returns immediately (in addition to the I / O call itself).

- ioctlsocket: , rcv:

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

:

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

- . , , WSAEWOULDBLOCK

, Windows . :

  • Overlapped I/O. , .
  • . , .
  • . UI- .
0

Source: https://habr.com/ru/post/1743318/


All Articles