#include <sys/select.h> /* According to POSIX .1-2001 */
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h> /*According to earlier standards*/
从键盘,socket中读数据时,数据到来时刻是随机的,使用select函数来设置超时响应。
示例:
select 函数会修改fd_set ,timeval的值,所以,每次循环需要重新设置。
#include <stdio.h> #include <sys/select.h> #include <string.h> #include <unistd.h> int main() { int fd = 0; int ret; char buf[11]; fd_set readfds; struct timeval timeout; while(1) { FD_ZERO(&readfds); FD_SET(fd,&readfds); timeout.tv_sec = 10; timeout.tv_usec = 0; ret = select(8,&readfds,NULL,NULL,&timeout); if(ret == 0) { printf("No data coming in. Timeout\n"); } else { memset(buf,0,11); if(read(fd,buf,10) != -1) { printf("%s",buf); } } } return 0; }