加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 设置读取stdin的超时时间

发布时间:2020-12-16 06:01:27 所属栏目:百科 来源:网络整理
导读:有没有办法暂停从stdin的阅读,以便程序不要挂起太久? read(0,var,numberofbytes); 解决方法 您可以使用 ncurses,或者您不想使用,可以使用本 blog post中所述的选择.基本上,您可以使用select并指定超时.如果stdin FD被设置,那么你可以安全地读取,不会阻塞.如
有没有办法暂停从stdin的阅读,以便程序不要挂起太久?
read(0,var,numberofbytes);

解决方法

您可以使用 ncurses,或者您不想使用,可以使用本 blog post中所述的选择.基本上,您可以使用select并指定超时.如果stdin FD被设置,那么你可以安全地读取,不会阻塞.如果你想要更多的信息选择,请检查 this,当然是 wikipedia.这是一个方便的电话来了解.

编辑:我觉得被迫提供代码,所以在这里是直接从博客文章与一些评论.

// 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,&tv);
    // return 0 if STDIN is not ready to be read.
    return FD_ISSET(STDIN_FILENO,&fds);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读