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

标签 c posix

有没有办法使从标准输入的读取超时,以使程序不会挂起太长时间?

read(0, var, numberofbytes);

最佳答案

您可以使用ncurses或者如果您不想,您可以按照此 blog post 中的描述使用 select 。基本上,您可以使用 select 并指定超时。如果设置了 stdin FD,那么您可以安全地读取它并且不会阻塞。如果您想了解有关 select 的更多信息,请查看 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, NULL, &tv);
    // return 0 if STDIN is not ready to be read.
    return FD_ISSET(STDIN_FILENO, &fds);
}

关于c - 设置读取 stdin 的超时时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683824/

相关文章:

c - System V——后进先出方式

c - "while"循环和 "do while"循环的区别

c - EZXML 解析器 C 和 UTF-8 字符集

c - 以特定方式打印出姓名

c++ - 为什么 stdarg.h 有一个宏 « __va_size »?

c++ - 使用指定的运行超时从 C++ 执行另一个程序

c++ - 指针减法和替代方案

Java时间忽略夏令时规则

c - 使用 mmap 的共享变量导致分段违规 (SIGSEGV)

linux - 并行运行 sed