Reputation: 5397
I have a POSIX thread which reads from the non-blocking anonymous pipe (marked with O_NONBLOCK
flag). When thread is stopping (because of errors for example) I want to check if there is something left in pipe (in its internal buffer). If pipe has data - run new thread with the same read descriptor (it is shared between threads) so the new thread can continue reading from pipe. If pipe is empty - close pipe and do nothing.
So I need to check if pipe is empty without removing data from pipe (as regular read
will do). Is there any way to do it?
P.S. I think setting count = 0
in read(int fd, void *buf, size_t count);
may help but the documentation sais that it is some kind of undefined behavior:
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.
Upvotes: 2
Views: 308
Reputation: 6866
I believe you want poll or select, called with a zero timeout.
Short description from the select() docs:
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).
...and the poll() docs:
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.
Upvotes: 2