linux select 学习

本文展示了一个使用C语言编写的程序示例,该程序利用select函数来监听标准输入和打开文件的描述符,以便检测是否有数据输入。通过设置文件描述符集并等待最多五秒的时间,程序可以有效地检测到数据的可用性。

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

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

int
main(void)
{
    fd_set rfds;
    struct timeval tv;
    int retval;

    int rof = open("aa.tt", O_RDONLY);
    printf("open aa.tt with fd is %d\n", rof);

    /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(0, &rfds);
    FD_SET(rof, &rfds);
    printf("FD_ISET: %d\n", FD_ISSET(0, &rfds));

    /* Wait up to five seconds. */
    tv.tv_sec = 5;
    tv.tv_usec = 0;

    retval = select(rof + 1, &rfds, NULL, NULL, &tv);
    /* Don't rely on the value of tv now! */

    if (retval == -1)
        perror("select()");
    else if (retval)
    {
        printf("retval is %d\n", retval);
        printf("Data is available now.\n");
        char cc[20]={0};
        int rreaded = read(0, cc, 19);
        printf("rreaded is :%d\n", rreaded);
        read(rof, cc+rreaded, 19-rreaded);
        printf("data is %s\n", cc);
        /* FD_ISSET(0, &rfds) will be true. */
    }
    else
        printf("No data within five seconds.\n");

    close(rof);

    exit(EXIT_SUCCESS);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值