栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

超时功能

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

超时功能

该虚拟程序可能会帮助您:

#include <stdio.h>#include <unistd.h>#include <sys/time.h>#include <sys/types.h>#define WAIT 3int main (){    char name[20] = {0}; // in case of single character input    fd_set          input_set;    struct timeval  timeout;    int  ready_for_reading = 0;    int  read_bytes = 0;        FD_ZERO(&input_set );        FD_SET(0, &input_set);        timeout.tv_sec = WAIT;    // WAIT seconds    timeout.tv_usec = 0;    // 0 milliseconds        printf("Enter Username: (in %d seconds)n", WAIT);    printf("Time start now!!!n");        ready_for_reading = select(1, &input_set, NULL, NULL, &timeout);        if (ready_for_reading == -1) {                printf("Unable to read your inputn");        return -1;    }    if (ready_for_reading) {        read_bytes = read(0, name, 19);        if(name[read_bytes-1]=='n'){        --read_bytes;        name[read_bytes]='';        }        if(read_bytes==0){ printf("You just hit entern");        } else { printf("Read, %d bytes from input : %s n", read_bytes, name);        }    } else {        printf(" %d Seconds are over - no data input n", WAIT);    }    return 0;}

更新:
这是经过测试的代码。

另外,我从man那里得到了一些提示

select
。本手册已包含一个代码段,该代码段可用于从终端读取内容,并且在无活动的情况下会在5秒内超时。

如果代码编写得不够好,请做一个简短的解释:

  1. 我们将输入流(
    fd = 1
    )添加到FD集。
  2. 我们发起
    select
    呼叫以侦听为任何活动创建的此FD集。
  3. 如果在此
    timeout
    期间内发生任何活动,则通过
    read
    调用读取该活动。
  4. 如果没有活动,则会发生超时。

希望这可以帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408706.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号