LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 615|回复: 2

select()函数

[复制链接]
发表于 2004-3-23 20:11:23 | 显示全部楼层 |阅读模式
各位有没有使用过select函数,它是应用在哪个情况下的?请教各位。
发表于 2004-3-23 20:28:20 | 显示全部楼层

  1. /*  select()  check for files that are ready for reading or writing
  2. #include <sys/time.h>
  3. int select( int width,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,
  4.             struct timeval * timeout );
  5. FD_SET( int fd, fd_set * fdset );
  6. FD_CLR( int fd, fd_set * fdset );
  7. FD_ISSET( int fd, fd_set * fdset );
  8. FD_ZERO( fd_set * fdset );
  9. FD_ZERO(&fdset)             Initializes a descriptor set fdset to the null set.
  10. FD_SET(fd, &fdset)          Add the file descriptor fd to the set fdset.
  11. FD_CLR(fd, &fdset)          Removes fd from fdset.
  12. FD_ISSET(fd, &fdset)        Is nonzero if fd is a member of fdset; otherwise, zero.
  13. This example opens a console and a serial port for read mode, and calls select()
  14. with a 5 second timeout. It waits for data to be available on either descriptor. */
  15. #include <unistd.h>
  16. #include <stdlib.h>
  17. #include <fcntl.h>
  18. #include <sys/time.h>
  19. int main( void )
  20. {
  21.     int console, serial;
  22.     struct timeval tv;
  23.     fd_set rfd;
  24.     int n;
  25.     if( ( console = open( "/dev/con1", O_RDONLY ) ) == -1
  26.     ||    ( serial  = open( "/dev/ser1", O_RDONLY ) ) == -1 ) {
  27.       perror( "open" );
  28.       return EXIT_FAILURE;
  29.     }
  30.     FD_ZERO( &rfd );
  31.     FD_SET( console, &rfd );
  32.     FD_SET( serial,  &rfd );
  33.     tv.tv_sec = 5; /* set a 5 second timeout */
  34.     tv.tv_usec = 0;
  35.     switch ( n = select( 1 + max( console, serial ),&rfd, 0, 0, &tv ) ) {
  36.       case -1:
  37.             perror( "select" );
  38.             return EXIT_FAILURE;
  39.       case  0:
  40.             puts( "select timed out" );
  41.             break;
  42.       default:
  43.             printf( "%d descriptors ready ...\n", n );
  44.             if( FD_ISSET( console, &rfd ) )
  45.                           puts( " -- console descriptor has data pending" );
  46.             if( FD_ISSET( serial, &rfd ) )
  47.                           puts( " -- serial descriptor has data pending" );
  48.      }
  49.     return EXIT_SUCCESS;
  50. }
  51. /*int select( int width,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,
  52.           struct timeval * timeout ); */
复制代码
发表于 2004-3-23 23:39:29 | 显示全部楼层
首先设定检测的套接字
然后select检测是否有套接字准备完毕(比如有socket连接)同时把检测的套接字集“清空”,请特别注意哦.写错了,应该是FD_ISSET宏晴空的~
select返回的是准备完毕的套接字数目
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表