首先解釋幾個名詞
阻塞|非阻塞、同步|異步
同步和異步僅僅是關于所關注的消息如何通知的機制,而不是處理消息的機制.也就是說,同步的情況下,是由處理消息者自己去等待消息是否被觸發,而異步的情況下是由觸發機制來通知處理消息者。
阻塞和非阻塞,這兩個概念與程序等待消息(無所謂同步或者異步)時的狀態有關。
同步/異步與阻塞/非阻塞是兩組不同的概念,它們可以共存組合。
Select
函數原型:
int select(int maxfdp,//所有文件描述符的最大值加1
fd_set *readfds,//關注的可讀描述符集
fd_set *writefds,//關注的可寫描述符集
fd_set *errorfds,//要關注的異常描述符集
struct timeval *timeout//超時時間
);
//從觸摸屏讀取數據
int ReadFunc(int fd, char *buf, int len)
{
fd_set fset;
struct timeval tv;
int rval;
FD_ZERO(&fset);
FD_SET(fd, &fset);
tv.tv_sec = 1;
tv.tv_usec = 0;
int pos = 0;
int ret = 0;
while(1){
if ((rval = select( fd+1, &fset, NULL, NULL, &tv)) < 0)
{
if (errno == EINTR)
continue;
else
rval = 0;
}
else if (rval)
{
if(FD_ISSET(fd, &fset)){
if(len > 50){
ret = read(fd, buf, len);
}else{
while(len){
ret = read(fd, buf+pos, len-ret);
len -= ret;
pos += ret;
}
}
}
/* if ( rval<0 && errno != ENODEV) */
/* { perror("read"); */
/* } */
}
return rval;
}
}