首先解釋幾個(gè)名詞
阻塞|非阻塞、同步|異步
同步和異步僅僅是關(guān)于所關(guān)注的消息如何通知的機(jī)制,而不是處理消息的機(jī)制.也就是說(shuō),同步的情況下,是由處理消息者自己去等待消息是否被觸發(fā),而異步的情況下是由觸發(fā)機(jī)制來(lái)通知處理消息者。
阻塞和非阻塞,這兩個(gè)概念與程序等待消息(無(wú)所謂同步或者異步)時(shí)的狀態(tài)有關(guān)。
同步/異步與阻塞/非阻塞是兩組不同的概念,它們可以共存組合。
Select
函數(shù)原型:
int select(int maxfdp,//所有文件描述符的最大值加1
fd_set *readfds,//關(guān)注的可讀描述符集
fd_set *writefds,//關(guān)注的可寫(xiě)描述符集
fd_set *errorfds,//要關(guān)注的異常描述符集
struct timeval *timeout//超時(shí)時(shí)間
);
//從觸摸屏讀取數(shù)據(jù)
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;
}
}