Sunday, June 9, 2013

Related Topic: Things you should know when using select()

Be really careful with your code when you use select function. Select() function is frequently used in multiprocessing programming and network programming to coordinate different processes. Very likely, the select function appears in infinite loop to catch any incoming messages. The regular order to use select function is
1) zero out the object of type fd_set
2) bind the file descriptor you want to monitor with the fd_set object 
3) find out the largest file descriptor
4) set up the timeval structure to specify how long this select function will be used if it's not NULL

The following code shows how the select monitors the reading end of a pipe. 


//initialize variables
fd_set input;
int max_fd;
int n; 
struct timeval timeout;
 
while(1)
{
 //set up time interval, 1 second
 timeout.tv_sec  = 1;
 timeout.tv_usec = 0; 
 //set up select function
 FD_ZERO(&input);
 FD_SET(fd_pipe_in[0], &input);
 max_fd=fd_pipe_in[0]+1;
 n=select(max_fd, &input, NULL, NULL, &timeout);
 if(n<0)
 perror("select() failed");
 // if nothing happens in this period
 else if(n==0)
 {
  //...
 }
 // if something is on the reading end of the pipe
 else
 {
  if(FD_ISSET(fd_pipe_in[0], &input))
   { 
    //......
   } 
 }
} 

No comments:

Post a Comment