}
That last line—system("stty cooked");—is necessary because the terminal characteristics
persist after the program finishes. If a program sets the terminal into a funny mode, it will stay in a
funny mode. This is quite unlike, say, setting an environment variable, which disappears when the
process does.
Raw I/O achieves a blocking read—if no character is available, the process waits there until one
comes in. If you need a nonblocking read, you can use the ioctl() (I/O control) system call. It
provides a fine level of control over terminal characteristics, and can tell you if a key has been pressed
under SVr4. This code uses an ioctl to only do a read if there is a character waiting to be read. This
type of I/O is known as polling, as you continually ask the device for its opinion on whether it has a
character to give you yet.
#include <sys/filio.h>
int kbhit()
{
int i;
ioctl(0, FIONREAD, &i);
return i; / return a count of chars available to read /
}
main()
{
int i = 0;
intc='';
system("stty raw -echo");
printf("enter 'q' to quit \n");
for (;c!='q';i++) {
if (kbhit()) {
c=getchar();
printf("\n got %c, on iteration %d",c, i);
}
}
system("stty cooked echo");
}
Handy Heuristic
Check errno After Library Calls
Whenever you're using system calls (like ioctl()), it's a good idea to check the global