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

前端之家收集整理的这篇文章主要介绍了c – 设置读取stdin的超时时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法暂停从stdin的阅读,以便程序不要挂起太久?
  1. read(0,var,numberofbytes);

解决方法

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

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

  1. // if != 0,then there is data to be read on stdin
  2. int kbhit()
  3. {
  4. // timeout structure passed into select
  5. struct timeval tv;
  6. // fd_set passed into select
  7. fd_set fds;
  8. // Set up the timeout. here we can wait for 1 second
  9. tv.tv_sec = 1;
  10. tv.tv_usec = 0;
  11.  
  12. // Zero out the fd_set - make sure it's pristine
  13. FD_ZERO(&fds);
  14. // Set the FD that we want to read
  15. FD_SET(STDIN_FILENO,&fds); //STDIN_FILENO is 0
  16. // 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.
  17. // the last parameter is the timeout. select will return if an FD is ready or
  18. // the timeout has occurred
  19. select(STDIN_FILENO+1,&fds,NULL,&tv);
  20. // return 0 if STDIN is not ready to be read.
  21. return FD_ISSET(STDIN_FILENO,&fds);
  22. }

猜你在找的C&C++相关文章