££i nclude
££i nclude
¶¨Ò庯Êý 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
££i nclude
££i nclude
££i nclude
££i nclude
££i nclude
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;
}
}
}
ÓÃÀ´Ñ»·¶ÁÈ¡¼üÅÌÊäÈë