实例1:监听标准输入
#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#define STDIN 0
int main()
{
int n, flag;
char buf[80];
fd_set fds;
struct timeval tv;
int fd = STDIN;
printf("type \"eXit\" to exit.\n");
flag = 1;
while(1 == flag)
{
tv.tv_sec=10;
tv.tv_usec=0;
FD_ZERO(&fds);
FD_SET(fd,&fds);
switch(select(fd+1, &fds, NULL, NULL, &tv))
{
case -1: // select错误
printf("返回错误。\n");
flag = -1;
break;
case 0: //再次轮询
printf("超时。\n");
break;
default:
if(FD_ISSET(fd, &fds))
{
fgets(buf, 20, stdin);
n = strlen(buf);
if('\n' == buf[n-1])
buf[n-1] = '\0';
printf("数据:%s\n", buf);
if(0 == strcmp(buf, "eXit")) //退出程序?
{
flag = 0;
break;
}
}
break;
}
}
return flag;
}
运行结果示例:
# ./select
type "eXit" to exit.
da
数据:da
wert
数据:wert
超时。
超时。
eXit
数据:eXit
#
5693

被折叠的 条评论
为什么被折叠?



