linux c語言 select函數用法(zz)

linux c語言 select函數用法

   
表頭文件
#i nclude<sys/time.h>
#i nclude<sys/types.h>
#i nclude<unistd.h>
定義函數
int select(int n,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,struct timeval * timeout);
函數說明
select()用來等待文件描述詞狀態的改變。參數n代表最大的文件描述詞加1,參數readfds、writefds 和exceptfds 稱爲描述詞組,是用來回傳該描述詞的讀,寫或例外的狀況。底下的宏提供了處理這三種描述詞組的方式:
FD_CLR(inr fd,fd_set* set);用來清除描述詞組set中相關fd 的位
FD_ISSET(int fd,fd_set *set);用來測試描述詞組set中相關fd 的位是否爲真
FD_SET(int fd,fd_set*set);用來設置描述詞組set中相關fd的位
FD_ZERO(fd_set *set); 用來清除描述詞組set的全部位
參數
timeout爲結構timeval,用來設置select()的等待時間,其結構定義如下
struct timeval
{
time_t tv_sec;
time_t tv_usec;
};
返回值
如果參數timeout設爲NULL則表示select()沒有timeout。
錯誤代碼
執行成功則返回文件描述詞狀態已改變的個數,如果返回0代表在描述詞狀態改變前已超過timeout時間,當有錯誤發生時則返回-1,錯誤原因存於errno,此時參數readfds,writefds,exceptfds和timeout的值變成不可預測。
EBADF 文件描述詞爲無效的或該文件已關閉
EINTR 此調用被信號所中斷
EINVAL 參數n 爲負值。
ENOMEM 核心內存不足
範例
常見的程序片段:fs_set readset;
FD_ZERO(&readset);
FD_SET(fd,&readset);
select(fd+1,&readset,NULL,NULL,NULL);
if(FD_ISSET(fd,readset){……}

下面是linux環境下select的一個簡單用法

#i nclude <sys/time.h>
#i nclude <stdio.h>
#i nclude <sys/types.h>
#i nclude <sys/stat.h>
#i nclude <fcntl.h>
#i nclude <assert.h>

int main ()
{
  int keyboard;
  int ret,i;
  char c;
  fd_set readfd;
  struct timeval timeout;
  keyboard = open("/dev/tty",O_RDONLY | O_NONBLOCK);
  assert(keyboard>0);
  while(1)
    {
  timeout.tv_sec=1;
  timeout.tv_usec=0;
  FD_ZERO(&readfd);
  FD_SET(keyboard,&readfd);
  ret=select(keyboard+1,&readfd,NULL,NULL,&timeout);
  if(FD_ISSET(keyboard,&readfd))
    {
      i=read(keyboard,&c,1);
          if('\n'==c)
          continue;
      printf("hehethe input is %c\n",c);
    
       if ('q'==c)
       break;
      }
  }
}
用來循環讀取鍵盤輸入

2007年9月17日,將例子程序作一修改,加上了time out,並且考慮了select得所有的情況:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>

int main ()
{
  int keyboard;
  int ret,i;
  char c;
  fd_set readfd;
  struct timeval timeout;
  keyboard = open("/dev/tty",O_RDONLY | O_NONBLOCK);
  assert(keyboard>0);
  while(1)
  {
      timeout.tv_sec=5;
      timeout.tv_usec=0;
      FD_ZERO(&readfd);
      FD_SET(keyboard,&readfd);
      ret=select(keyboard+1,&readfd,NULL,NULL,&timeout);

      //select error when ret = -1
      if (ret == -1)
          perror("select error");

      //data coming when ret>0
      else if (ret)
      {
          if(FD_ISSET(keyboard,&readfd))
          {
              i=read(keyboard,&c,1);
              if('\n'==c)
                  continue;
              printf("hehethe input is %c\n",c);

              if ('q'==c)
              break;
          }
      }

      //time out when ret = 0
      else if (ret == 0)
          printf("time out\n");
  }
}

[來源]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章