2

Given the following setup:

  • child process has been opened for reading (for example via popen())
  • child's stdout has been set to line buffered (_IOLBF)
  • parent monitors for data on child's stdout (select(), poll() or epoll())
  • parents reads from child's stdout once data available (fgets() or getline())

Seeing how the stream has been set to line buffered, can we safely assume that there will only ever be one single line to read, or are there possible scenarios where there are multiple lines waiting in the buffer, meaning we have to call fgets() or getline() until they hit EOF (or EAGAIN / EWOULDBLOCK for non-blocking streams)?

domsson
  • 4,553
  • 2
  • 22
  • 40
  • Not quite what you are asking, but one thing that is often seen here when using `fgets` is an "extra" (the same) last line apparently read due to using `feof` incorrectly and not checking the return value from `fgets`. – Weather Vane May 25 '20 at 11:34
  • 3
    If the child is 'faster' than the parent I don't see a reason why there could **not** be several lines in the buffer – Ingo Leonhardt May 25 '20 at 11:37

1 Answers1

3

can we safely assume that there will only ever be one single line to read, or are there possible scenarios where there are multiple lines waiting in the buffer, meaning we have to call fgets() or getline() until they hit EOF (or EAGAIN / EWOULDBLOCK for non-blocking streams)?

I steal the relevant part from this answer (that is in turn linked to C11 standard):

When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.

So, line buffered doesn't mean that all data is buffered in a single line, but instead that the data is sent as soon as there's a new line.

As a consequence, the answer to your question is that are possible scenarios in which multiple line are waiting to be read (depending, of course, on what is actually sent from your child process).

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39