如何同时从标准输入和套接字进行轮询?

How to poll simultaneously from stdin and from sockets?

我想编写一个 C 程序来同时等待来自 stdin 和套接字的数据。为此,我想使用 poll().

但我似乎误解了 poll 如何在 stdin 上工作...我希望它的行为就像它在套接字上的行为一样,即:报告 POLLIN 当且仅当如果我真的在终端输入了一些东西(最好也按下 RETURN)。

为了测试这个假设是否正确,我写了一个简单的程序,poll仅在 stdin:

#include <poll.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main()
{
  int ret_poll; ssize_t ret_read;
  struct pollfd input[1] = {{fd: 0, events: POLLIN}};
  char buff[100];
  while(1) {
    ret_poll = poll(input, 1, 0);
    printf("ret_poll:\t%d\nerrno:\t%d\nstrerror:\t%s\n",
        ret_poll, errno, strerror(errno));
    ret_read = read(0, buff, 99);
    printf("ret_read:\t%zd\nerrno:\t%d\nstrerror:\t%s\nbuff:\t%s\n",
        ret_read, errno, strerror(errno), buff);
  }
}

然而,我发现在上面的例子中(当我告诉pollstdin等待POLLIN时)poll returns立即全部时间,无论我是否真的输入了一些东西。然后,当然是 stdin 块上的后续 read()。所以我想这意味着我不能同时等待从输入到终端和从套接字:(

是否可以在 stdin 上仅在实际有数据可读时才在 poll 上报告 POLLIN

正如@Roecrew 上面提到的那样,poll() returns 立即因为你给了 0 超时。正如手册页所说:

Note that the timeout interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the blocking interval may overrun by a small amount. Specifying a negative value in timeout means an infinite timeout. Specifying a timeout of zero causes poll() to return immediately, even if no file descriptors are ready.

如果你改变: ret_poll = poll(input, 1, 0);ret_poll = poll(input, 1, -1); 它会按您预期的那样工作。