Why does a call to read() hang waiting for a newline (C)?

66 Views Asked by At

Consider this program (a basic implementation of cat):

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>

int main() {
  char buffer[4096];
  ssize_t bytes_read;
  while ( ( bytes_read = read(STDIN_FILENO, buffer, sizeof buffer) ) > 0) {
    ssize_t bytes_written = write(STDOUT_FILENO, buffer, bytes_read);
    if (bytes_written == -1) return errno;
    assert(bytes_read == bytes_written);
  }
  if (bytes_read == -1) return errno;
  assert(bytes_read == 0);
  return 0;
}

I was wondering why this hangs waiting for read(2) input to be terminated with a \n, when I didn't specify something like readline().

My initial assumption for read was that it would return 0 whenever input wasn't available and the associated file descriptor open, and -1 (a common representation for EOF) when it was closed, and perhaps another negative integer for error.

After reading the manual, and writing the program, I was under the impression that read(2) would block until any input was available with size >0 and immediately return with that information; however, it seems the terminal causes it to block until it receives a \n character.

My question is: Why does this not adhere to my expectations, and what is really happening here?

0

There are 0 best solutions below