select函数的使用举例

本文介绍了一个使用C语言编程实现的简单程序,该程序利用select和ioctl系统调用来检测键盘输入,并能处理超时情况。通过FD_ZERO、FD_SET等函数设置文件描述符集,select用于等待I/O就绪状态,ioctl则用于获取输入缓冲区中的字符数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <sys/types.h> 
#include <sys/time.h> 
#include <stdio.h> 
#include <fcntl.h> 
#include <sys/ioctl.h> 
#include <unistd.h> 

int main() 
{ 
    char buffer[128]; 
    int result, nread; 
    fd_set inputs, testfds; 
    struct timeval timeout; 
    FD_ZERO(&inputs);//用select函数之前先把集合清零  
    FD_SET(0, &inputs);//把要检测的句柄——标准输入(0),加入到集合里。
    while(1) 
    { 
        testfds = inputs; 
        timeout.tv_sec = 2; 
        timeout.tv_usec = 500000; 
        result = select(FD_SETSIZE, &testfds, (fd_set *)0, (fd_set *)0, &timeout); 
        switch(result) 
        { 
            case 0: 
                printf("timeout\n"); 
	        break;
	    case -1: 
                perror("select\n"); 
                return 1; 
            default: 
                if(FD_ISSET(0, &testfds)) 
                { 
                    ioctl(0, FIONREAD, &nread);//取得从键盘输入字符的个数,包括回车。 
                    if(nread == 0) 
                    { 
                        printf("keyboard done\n"); 
                        return 0; 
                    } 
                    nread = read(0, buffer, nread); 
                    buffer[nread] = 0; 
                    printf("read %d from keyboard: %s", nread, buffer); 
               } 
               break; 
       } 
    } 
    return 0;
} 


学习资料参考于:

http://blog.youkuaiyun.com/piaojun_pj/article/details/5991968

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值