c - 如何检查非阻塞匿名管道是否有数据而不删除它

标签 c multithreading pipe posix

我有一个 POSIX 线程,它从非阻塞匿名管道(用 O_NONBLOCK 标记标记)读取。当线程停止时(例如由于错误)我想检查管道中(在其内部缓冲区中)是否还有东西。如果管道有数据 - 使用相同的读取描述符运行新线程(它在线程之间共享),以便新线程可以继续从管道读取。如果管道为空 - 关闭管道并且不执行任何操作。

因此,我需要检查管道是否为空,而不从管道中删除数据(就像常规的read那样)。有什么办法可以做到吗?

附注我认为在 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.

最佳答案

我相信你想要pollselect ,以零超时调用。

来自 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.

关于c - 如何检查非阻塞匿名管道是否有数据而不删除它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43709858/

相关文章:

linux - 负责配置进程数和线程数的Linux配置参数有哪些?

java - 如果返回值在同步块(synchronized block)之外声明/返回,方法是否是线程安全的?

windows - 如何使用管道将一个命令的输出重定向到另一个命令的输入?

java - 为什么一个线程阻塞了我的 JavaFX UI 线程?

shell - 从丑陋的命令行管道创建整洁的 shell 脚本

c - 使用管道实现异步行为

c - 减去两个时间间隔

c - 在 C 中使用 fwrite() 的 fseek() 之后,fread() 不工作

c - 当仅在中断期间读取变量时是否需要 volatile

c - 为什么我得到这个输出(整数和双重歧义)?