我有一个 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.
最佳答案
来自 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/