如何在不删除数据的情况下检查非阻塞匿名管道是否有数据

How to check if non-blocking anonymous pipe has data without removing it

我有一个 POSIX 线程,它从非阻塞匿名管道(标有 O_NONBLOCK 标志)读取。当线程停止时(例如由于错误)我想检查管道中是否还有东西(在其内部缓冲区中)。如果管道有数据 - 运行 具有相同读取描述符的新线程(它在线程之间共享),因此新线程可以继续从管道读取。如果管道是空的 - 关闭管道什么也不做。

所以我需要检查管道是否为空而不从管道中删除数据(正如常规 read 所做的那样)。有什么办法吗?

P.S。我认为在 read(int fd, void *buf, size_t count); 中设置 count = 0 可能会有所帮助,但文档说这是某种未定义的行为:

If count is zero, read() may detect the errors described below. In the absence of any errors, or if read() does not check for errors, a read() with a count of 0 returns zero and has no other effects.

我相信你想要 poll or select,以零超时调用。

来自 select() 文档的简短描述:

   select() and pselect() allow a program to monitor multiple file
   descriptors, waiting until one or more of the file descriptors become
   "ready" for some class of I/O operation (e.g., input possible).

...和 ​​poll() 文档:

   poll() performs a similar task to select(2): it waits for one of a
   set of file descriptors to become ready to perform I/O.