用select实现监控终端输入

时间:2023-03-09 00:01:38
用select实现监控终端输入

首先,从man手册里找到对select函数的描述,如下:

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);

其中:
   nfds : 指集合中所有文件描述符的范围,即所有文件描述符的最大值加1
   readfds / writefds : 监控文件读(写)属性,集合中有一个文件可读(写),返回值大于0;否则,根据timeout判断是否超时,若超时,返回值为0;若发生错误返回-1.若值为NULL,表示不关心集合中文件的读(写)属性。
   exceptfds : 监视文件异常错误
   timeout : 可以使select处于三种状态:
       1. NULL:阻塞,直到文件描述符集合中有文件发生变化为止;
       2. 0s 0ms: 非阻塞,不管文件描述符是否有变化,都立刻返回继续执行,文件无变化返回0,有变化返回一个正值;
       3. 大于0:在timeout时间内阻塞,超时时间之内有事件到来就返回了,否则在超时后不管怎样一定返回,返回值同上述。

select : 监控fd集合变化
 FD_CLR 在fd集合删除某个fd
 FD_ISSET 测试fd集合中的某个fd是否可以读写
 FD_SET 向fd集合中添加fd
 FD_ZERO 清空fd集合

0 : stdin 1 : stdout 2 : stderr

有了以上关于select的描述,下面附上程序:

 #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h> #define STDIN 0 int main()
{
//1. 初始化fd集合
fd_set fds;//定义fd集合
FD_ZERO(&fds);//清空fd集合
FD_SET(STDIN,&fds);//添加STDIN
//2. 监控fd集合 - 遍历集合方式
int ret = select(STDIN+,&fds,NULL,NULL,NULL);
if(ret == -)
{
perror("select");
exit();
} //3. 判断STDIN的读属性是否发生变化
if(FD_ISSET(STDIN,&fds))
printf("someone input a char!\n"); //4. 清空集合
FD_CLR(STDIN,&fds);
FD_ZERO(&fds);
return ;
}