I would like to be able to tell if a character special file would block if a character were read from it without actually reading a character from it. Can this be done?
You can do this from bash using a 0 timeout to
if read -t 0 then read data fi
To test a file descriptor other than stdin, say 3, use
-u 3. To find how many chars are ready on stdin you can use a small perl script:
#!/usr/bin/perl require 'sys/ioctl.ph'; $size = pack("L", 0); ioctl(*STDIN, FIONREAD(), $size) or die "ioctl fail: $!\n"; $size = unpack("L", $size); print "stdin ready: $size\n";
POSIX allows non-blocking, zero-character reads which "may detect and return errors", including that the read would block:
read operation checks for errors in such cases, if a read would block then
read will return -1 and set
EAGAIN (or possibly
EWOULDBLOCK for sockets, but you're asking about character devices).
From C or C++ you would normally use
pselect() to test if there is data ready for reading. You can do that without having to set the file descriptor mode to non-blocking.