2014年(41)
分类: LINUX
2014-04-23 21:14:39
一个select函数的例子
#include
#include
#include
#include
#include
int main()
{
struct timeval tv;
char buf[100] = "pig";
fd_set readfds;
tv.tv_sec = 4;
tv.tv_usec = 500000;
FD_ZERO(&readfds);
FD_SET(0, &readfds);
//scanf("%s", buf);
int flags = fcntl(1,F_GETFL,0);
flags |= O_NONBLOCK;
fcntl(1,F_SETFL,flags);//将标准输入设问非阻塞
printf("before select\n");
select(1, &readfds, NULL, NULL, &tv);//等待4.5秒,如果4.5秒内没有输入。则time out
printf("after select\n");
scanf("%s", buf);
if(FD_ISSET(0, &readfds))
{
printf("A key was pressed!\n");
}
else
{
printf("Time out.\n");
}
printf("buf:%s\n", buf);
return 0;
}