How can I find out if there are characters available for reading?

Q

How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available?

✍: Guest

A

These, too, are entirely operating-system-specific. Some versions of curses have a nodelay function. Depending on your system, you may also be able to use ``nonblocking I/O'', or a system call named select or poll, or the FIONREAD ioctl, or c_cc[VTIME], or kbhit, or rdchk, or the O_NDELAY option to open or fcntl. You can also try setting an alarm to cause a blocking read to time out after a certain interval (under Unix, look at alarm, signal, and maybe setitimer).
If what you're trying to do is read input from several sources without blocking, you will definitely want to use some kind of a ``select'' call, because a busy-wait, polling loop is terribly inefficient on a multitasking system.

2015-04-29, 1083👍, 0💬