【问题标题】:Check if stdin is empty检查标准输入是否为空
【发布时间】:2013-04-26 04:51:02
【问题描述】:

我搜索但没有得到这个问题的相关答案,我正在使用 linux 机器,我想检查标准输入流是否包含任何字符,而不从流中删除字符。

【问题讨论】:

  • C++ 还是 C?您的问题被标记为两者。
  • 我不确定您的问题是否具有明确的含义。想象一下 stdin 是一个管道(来自一个命令,它需要很长时间才能在其 stdout 上吐出它的第一个字符)。你可以做的是使用STDIN_FILENO(即0)作为文件描述符调用poll(2)。然后检查 stdin 是否可读...(即 read(2) 不会阻塞)。

标签: c++ c stdin


【解决方案1】:

cacho 在正确的路径上,但是 select 仅在您处理多个文件描述符时才需要,并且 stdin 不是 POSIX 文件描述符 (int);这是一个FILE *。如果你走那条路,你会想使用STDIN_FILENO。

这也不是一条非常干净的路线。我更喜欢使用poll。通过将 timeout 指定为 0,poll 将立即返回。

如果任何选定的文件上都没有发生任何定义的事件 描述符,poll() 应至少等待超时毫秒 在任何选定的文件描述符上发生的事件。 如果值 超时时间为 0,poll() 将立即返回。 如果值为 timeout 为 -1,poll() 将阻塞,直到发生请求的事件或 直到通话中断。

struct pollfd stdin_poll = { .fd = STDIN_FILENO
                           , .events = POLLIN | POLLRDBAND | POLLRDNORM | POLLPRI };
if (poll(&stdin_poll, 1, 0) == 1) {
    /* Data waiting on stdin. Process it. */
}
/* Do other processing. */

【讨论】:

【解决方案2】:

您可能想尝试select() 函数,并等待数据进入输入流。

说明:

select() 和 pselect() 允许程序监视多个文件 描述符,等到一个或多个文件描述符变为 为某种类型的 I/O 操作“准备好”(例如,可能的输入)。一份文件 如果可以执行描述符,则认为已准备好 相应的 I/O 操作(例如,read(2))而不阻塞。

在您的情况下,文件描述符将是 stdin

void yourFunction(){
    fd_set fds;
    struct timeval timeout;
    int selectRetVal;

    /* Set time limit you want to WAIT for the fdescriptor to have data, 
       or not( you can set it to ZERO if you want) */
    timeout.tv_sec = 0;
    timeout.tv_usec = 1;

    /* Create a descriptor set containing our remote socket
       (the one that connects with the remote troll at the client side).  */
    FD_ZERO(&fds);
    FD_SET(stdin, &fds);

    selectRetVal = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);

    if (selectRetVal == -1) {
        /* error occurred in select(),  */
        printf("select failed()\n");
    } else if (selectRetVal == 0) {
        printf("Timeout occurred!!! No data to fetch().\n");
        //do some other stuff
    } else {
        /* The descriptor has data, fetch it. */
        if (FD_ISSET(stdin, &fds)) {
            //do whatever you want with the data
        }
    }
}

希望对你有帮助。

【讨论】:

  • 感谢您的即时回复,但是,我不想等待输入流有数据,只是,如果流有数据,我需要做一些处理,如果它没有数据,做一些其他的处理。代码不应该等待输入,
  • 我仍然认为这可以帮助@51k,让我举个例子。
  • 对于 gcc c++,我不得不使用 0 而不是 stdin
猜你喜欢
  • 1970-01-01
  • 2019-11-15
  • 2012-02-03
  • 1970-01-01
  • 2018-05-26
  • 2015-08-10
  • 1970-01-01
  • 2021-11-22
  • 2015-01-11
相关资源
最近更新 更多