Thursday, November 29, 2007

Asynchronous Reading from Input

Intro
Normal working of a C program taking an input is done via the scanf method. The problem in scanf is that when we invoke scanf it waits until we input something i.e, our program is waiting for the user input. This valuable time could be used for processing other things. Let us consider an example of a chat client made using C. When we want to send some message we type them and send. In all other cases it is required that the chat client listens for incoming messages. This is impossible using the normal scanf method, because at all times it would be waiting for our input and there would not be any recieved messages in that time period. So the process of receiving information while checking for input is an example of asynchronous reading.

How ?

On Windows ...
On windows the input STDIN can be tested for data by the function kbhit()
defined on conio.h. A simple program template would be


#include <conio.h>

int main()
{
//...
while(1) //Main Process loop
{
//Other Process Block
{
/*
* Something else to do
*/

}
if(kbhit())
{
//Input present and process input
}
}
}

kbhit does not take any arguments, it returns 1 if there has been a keyboard hit i.e., a key has been pressed.
The key can be read using getch() or similar functions.

On Linux...
the same thing seems to be a bit different. There is no conio.h defined for linux so there is no kbhit function that can be used in linux. However linux has a set of functions that can be used to test any input for the presence of input. The following is the list of functions that are used to test the input for data.

#include <sys/time.h>

int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *errorfds, struct timeval *timeout);

void FD_SET(int fd, fd_set *fdset);

void FD_CLR(int fd, fd_set *fdset);

int FD_ISSET(int fd, fd_set *fdset);

void FD_ZERO(fd_set *fdset);

0 comments: