2

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.

Alexander Ushakov
  • 5,139
  • 3
  • 27
  • 50
  • Nitpick: the documentation for zero-sized reads describes _implementation-defined_, not undefined, behavior. Undefined behavior specifically means that *any* result is correct. My C professor used to say "undefined behavior means that it is technically valid for your computer to catch fire". :) – Snild Dolkow Apr 30 '17 at 18:39
  • Also, it feels to me that this should be a duplicate (I can't imagine that it hasn't been asked before), but I can't seem to find a good match. Hm. – Snild Dolkow Apr 30 '17 at 18:42
  • @SnildDolkow Believe me I've made really deep search before asking. – Alexander Ushakov Apr 30 '17 at 18:45
  • Yeah, I couldn't find a duplicate either, which was a bit surprising to me. :) – Snild Dolkow Apr 30 '17 at 18:46

1 Answers1

2

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.
Snild Dolkow
  • 6,669
  • 3
  • 20
  • 32