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