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 稱為描寫敘述詞組。是用來回傳該描寫敘述詞的讀,寫或例外的狀況。 底下的宏提供了處理這三種描寫敘述詞組的方式: |
參數
|
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");
}
}