设置阅读标准输入超时 [英] Set a timeout for reading stdin

查看:114
本文介绍了设置阅读标准输入超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法超时从标准输入读取为了使程序不挂太久?

 阅读(0,VAR,numberofbytes);


解决方案

您可以使用 ncurses的或如果你不不想的话,你可以使用select在此描述的博客文章。基本上,你可以使用选择并指定超时。如果标准输入FD设置,则可以通过它安全地读取并不会阻止。如果您想对选择更多资讯,请的出来,当然的维基百科。这是一个方便的电话了解。

编辑:我觉得有必要提供code,所以在这里它是,直接从博客帖子有一些意见

  //如果!= 0,再有就是要在标准输入读取数据
INT的kbhit()
{
    //超时结构传递到选择
    timeval结构电视;
    // FD_SET传递到选择
    FD_SET FDS;
    //设置超时时间。在这里我们可以等待1秒
    tv.tv_sec = 1;
    tv.tv_usec = 0;    //零出FD_SET - 确保它的质朴
    FD_ZERO(安培; FDS);
    //设置我们要读取的FD
    FD_SET(STDIN_FILENO,&安培; FDS); // STDIN_FILENO是0
    //选择需要在fdset的最后一个文件描述符值+ 1进行检查,
    //为读操作,fdset写道,和错误。我们只是传递读取。
    //最后一个参数是超时。如果选择的FD准备或将恢复
    //超时发生
    选择(STDIN_FILENO + 1,&安培; FDS,NULL,NULL,&安培;电视);
    //返回0,如果标准输入是不是准备好被读取。
    返回FD_ISSET(STDIN_FILENO,&安培; FDS);
}

Is there a way to timeout a reading from stdin in order for the program not to hang for too long ?

read(0, var, numberofbytes);

解决方案

You can use ncurses or if you don't want to, you can use select as described in this blog post. Basically, you can use select and specify the timeout. If the stdin FD is set, then you can read from it safely and won't block. If you want more info on select, check this out and of course wikipedia. It's a handy call to know about.

EDIT: I feel compelled to supply code, so here it is, straight from the blog post with some comments.

// if != 0, then there is data to be read on stdin
int kbhit()
{
    // timeout structure passed into select
    struct timeval tv;
    // fd_set passed into select
    fd_set fds;
    // Set up the timeout.  here we can wait for 1 second
    tv.tv_sec = 1;
    tv.tv_usec = 0;

    // Zero out the fd_set - make sure it's pristine
    FD_ZERO(&fds);
    // Set the FD that we want to read
    FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
    // select takes the last file descriptor value + 1 in the fdset to check,
    // the fdset for reads, writes, and errors.  We are only passing in reads.
    // the last parameter is the timeout.  select will return if an FD is ready or 
    // the timeout has occurred
    select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
    // return 0 if STDIN is not ready to be read.
    return FD_ISSET(STDIN_FILENO, &fds);
}

这篇关于设置阅读标准输入超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆