0

I am seeking some non-blocking function (will return any available input but will not wait for more input from the user) which will read any and all stdin data up to n into a buffer and return how many bytes were read.

int n_bytes = readn(&buff, length);
if (n_bytes > 0) {
...

My current attempt uses getchar() until EOF, but that waits for input. I would like to avoid multithreading if possible.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • non blocking console IO is platform dependant. What platform are you on – pm100 Feb 21 '22 at 19:28
  • @EricPostpischil I need a function which will not block if there are fewer data than requested – Nick Belanger Feb 21 '22 at 19:40
  • 3
    Does this answer your question? [Non-blocking call for reading descriptor](https://stackoverflow.com/questions/5616092/non-blocking-call-for-reading-descriptor) – kaylum Feb 21 '22 at 19:44
  • 1
    There are no non-blocking IO functions in the C standard. On the POSIX sice you can use [select](https://pubs.opengroup.org/onlinepubs/7908799/xsh/select.html) or [poll](https://pubs.opengroup.org/onlinepubs/7908799/xsh/poll.html) to determine availability of input data, or the [O_NONBLOCK](https://pubs.opengroup.org/onlinepubs/007904975/basedefs/fcntl.h.html) flag – n. m. could be an AI Feb 21 '22 at 19:48
  • 1
    Besides the answers at the question kaylum linked to, you might (1) use termios to set the terminal in "cbreak" or "raw" mode, or (2) use `ncurses`. – Steve Summit Feb 21 '22 at 19:50
  • 1
    _If_ `stdin` is a TTY device on a linux/posix system ... You will need to use `termios` [as Steve suggested] to put the _kernel_ TTY driver into "raw" mode. Otherwise, it will hold onto chars until a newline is entered and then "release" them all at once. This is required even with `O_NONBLOCK` or `select/poll`. AFAIK, with `termios`, the other methods _may_ not be needed. – Craig Estey Feb 21 '22 at 21:35
  • When you say "I need a function which will not block if there are fewer data than requested", does that include the case that there is no data? What if the user has typed a couple of characters but has not yet hit the Enter key? If you want to read a partial line, how do you plan on supporting line-editing (eg., the backspace key), or are you also thinking about not allowing the user to correct their mistakes? – rici Feb 21 '22 at 21:36

0 Answers0