|
发表于 2004-3-23 20:28:20
|
显示全部楼层
- /* select() check for files that are ready for reading or writing
- #include <sys/time.h>
- int select( int width,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,
- struct timeval * timeout );
- FD_SET( int fd, fd_set * fdset );
- FD_CLR( int fd, fd_set * fdset );
- FD_ISSET( int fd, fd_set * fdset );
- FD_ZERO( fd_set * fdset );
- FD_ZERO(&fdset) Initializes a descriptor set fdset to the null set.
- FD_SET(fd, &fdset) Add the file descriptor fd to the set fdset.
- FD_CLR(fd, &fdset) Removes fd from fdset.
- FD_ISSET(fd, &fdset) Is nonzero if fd is a member of fdset; otherwise, zero.
- This example opens a console and a serial port for read mode, and calls select()
- with a 5 second timeout. It waits for data to be available on either descriptor. */
- #include <unistd.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <sys/time.h>
- int main( void )
- {
- int console, serial;
- struct timeval tv;
- fd_set rfd;
- int n;
- if( ( console = open( "/dev/con1", O_RDONLY ) ) == -1
- || ( serial = open( "/dev/ser1", O_RDONLY ) ) == -1 ) {
- perror( "open" );
- return EXIT_FAILURE;
- }
- FD_ZERO( &rfd );
- FD_SET( console, &rfd );
- FD_SET( serial, &rfd );
- tv.tv_sec = 5; /* set a 5 second timeout */
- tv.tv_usec = 0;
- switch ( n = select( 1 + max( console, serial ),&rfd, 0, 0, &tv ) ) {
- case -1:
- perror( "select" );
- return EXIT_FAILURE;
- case 0:
- puts( "select timed out" );
- break;
- default:
- printf( "%d descriptors ready ...\n", n );
- if( FD_ISSET( console, &rfd ) )
- puts( " -- console descriptor has data pending" );
- if( FD_ISSET( serial, &rfd ) )
- puts( " -- serial descriptor has data pending" );
- }
- return EXIT_SUCCESS;
- }
- /*int select( int width,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,
- struct timeval * timeout ); */
复制代码 |
|