#include <sys/time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/select.h>
int main()
{
int keyboard;
int ret,i;
char c;
fd_set readfd;
struct timeval timeout;
//非阻塞地读取终端上的输入信息,/dev/tty当前终端
keyboard=open("/dev/tty",O_RDONLY | O_NONBLOCK);
//如果条件返回错误,则终止程序执行
assert(keyboard>0);
while(1)
{
timeout.tv_sec=5;//超时时间设置为5s
timeout.tv_usec=0;
FD_ZERO(&readfd); //清空可读的fd集合
//把打开终端的fd加入到可读fd集合中
FD_SET(keyboard,&readfd);
//调用select查看是否有可读的fd
ret=select(keyboard+1, &readfd, NULL, NULL, &timeout);
//表示调用select失败
if(ret==-1)
perror("select error");
else if(ret)
{
//判断终端的fd是否在可读描述符集合中
if(FD_ISSET(keyboard,&readfd))
{
i=read(keyboard, &c, 1);
if(c=='\n')
continue;
printf("The input is %c\n",c);
if(c=='q')
break;
}
}
//表示等待时间超时
else if(ret==0)
printf("time out\n");
}
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/select.h>
int main()
{
int keyboard;
int ret,i;
char c;
fd_set readfd;
struct timeval timeout;
//非阻塞地读取终端上的输入信息,/dev/tty当前终端
keyboard=open("/dev/tty",O_RDONLY | O_NONBLOCK);
//如果条件返回错误,则终止程序执行
assert(keyboard>0);
while(1)
{
timeout.tv_sec=5;//超时时间设置为5s
timeout.tv_usec=0;
FD_ZERO(&readfd); //清空可读的fd集合
//把打开终端的fd加入到可读fd集合中
FD_SET(keyboard,&readfd);
//调用select查看是否有可读的fd
ret=select(keyboard+1, &readfd, NULL, NULL, &timeout);
//表示调用select失败
if(ret==-1)
perror("select error");
else if(ret)
{
//判断终端的fd是否在可读描述符集合中
if(FD_ISSET(keyboard,&readfd))
{
i=read(keyboard, &c, 1);
if(c=='\n')
continue;
printf("The input is %c\n",c);
if(c=='q')
break;
}
}
//表示等待时间超时
else if(ret==0)
printf("time out\n");
}
return 0;
}