c - 设置读取标准输入的超时时间

标签 c posix

有没有一种方法可以使从 stdin 读取超时以使程序不会挂起太久?

read(0, var, numberofbytes);

最佳答案

您可以使用 ncurses或者,如果您不想,可以按照本 blog post 中的说明使用 select .基本上,您可以使用 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, NULL, &tv);
    // return 0 if STDIN is not ready to be read.
    return FD_ISSET(STDIN_FILENO, &fds);
}

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

相关文章:

python - 修改静态变量是线程安全的吗?

c++ - 在 C/C+ 中将 16 位线性 PCM 音频转换为 32 位 float 的最佳方式?

线程可以修改 pthread_create 参数吗?

ios - 在 iOS 上调用 posix_spawn

c - 仅在 POSIX 上打开文件

c - 如何在 Linux 中使用 POSIX pthreads 将整数从文件写入缓冲区?

c - UDP套接字: server sending file to client Address family not supported by protocol family

c++ - 一条定义规则 : Can corresponding entities have different names?

c++ - 如何将结构从 C++ 传递给 C?

c - UNIX 域套接字 (PF_UNIX) 上的 send() 失败并出现 ENOBUFS 错误