zoukankan      html  css  js  c++  java
  • 17初识select

    多路复用 select

    同时监控多个文件描述符的输入输出

    <sys/types.h>

    <sys/times.h>

    <sys/select.h>

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

    FD_ISSET(int fd, fd_set *fdset)      //判断fd是否就绪

    FD_SET(int fd,  fd_set *fdset)       //增加fd  到 fdset

    FD_CLR(int fd,  fd_set *fdset)       //从fdset中删除 fd

    FD_ZERO(fd_set *fdset)               //清空fdset

    函数解析:

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

    nfds:           监控文件描述符的最大值 + 1

    readfds:      监控的可读文件描述符集合

    writefds:      监控的可写文件描述符集合

    exceptfds:   监控的异常文件描述符集合

    timeout:       超时时间, NULL 表示一直等待

    select 阻塞 timeout 时间,时间到后,返回

    返回值:返回已准备好的文件个数, 0 表示没有fd准备好,-1 表示出错

    例子:

    void  testSelect()

    {

          int fd=0;

          char buf[128];

          fd_set fset;

         

          struct timeval tv;

          tv.tv_usec=0;   

          while(1)

          {

               FD_ZERO(&fset);

               FD_SET(STDIN_FILENO,&fset);

               tv.tv_sec=5;

               fprintf(stderr,"input:");

               int nRet=select(fd+1,&fset,NULL,NULL,&tv);

               if(nRet==-1)

               {

                     perror("select error!");        

                     return ;

               }

               else if(nRet==0)

               {

                     printf(" no input ");

               }

               else

               {

                     if(FD_ISSET(STDIN_FILENO,&fset))

                     {

                          scanf("%s",buf);

                          printf("your input:%s ",buf);

                     }

               }

          }

         

    }

  • 相关阅读:
    启用div作为编辑器 添加contentEditalbe属性
    AngularJs 通过 ocLazyLoad 实现动态(懒)加载模块和依赖-转
    angularjs的懒加载
    JavaScript 中的this指向问题
    Project Euler:Problem 41 Pandigital prime
    Android 消息机制
    新西兰天维网登录发送明文password
    使用Reveal来查看别人的APP界面+白苹果不刷机解决方式
    Android中List循环遍历性能对照
    2016年最新苹果开发人员账号注冊申请流程最强具体解释!
  • 原文地址:https://www.cnblogs.com/gd-luojialin/p/9216006.html
Copyright © 2011-2022 走看看