title: C: Wait for n characters on a blocking socket with timeout
body: <p>I need to wait for n bytes of data (count is known) on a serial port or socket on Linux.
  Currently I use a loop with poll, measure the time and decrement the timeout:</p>
  
  <pre><code>static int int_read_poll(int fd, uint8_t *buffer, size_t count, int timeout)
  {
      struct pollfd pfd;
      int rc;
  
      pfd.fd = fd;
      pfd.events = POLLIN;
  
      rc = poll(&amp;pfd, 1, timeout);
      if (rc &lt; 0) {
          perror("poll");
          return 0;
      }
  
      if (rc &gt; 0) {
          if (pfd.revents &amp; POLLIN) {
              rc = read(fd, buffer, count);
              return rc;
          }
      }
      return 0;
  }
  
  static int int_read_waitfor(int fd, uint8_t *buffer, size_t count, int timeout)
  {
      int rc;
      struct timespec start, end;
      int delta_ms;
      int recv = 0;
  
      do {
          clock_gettime(CLOCK_MONOTONIC_RAW, &amp;start);
              rc = int_read_poll(fd, buffer + recv, count - recv, timeout);
          clock_gettime(CLOCK_MONOTONIC_RAW, &amp;end);
          delta_ms = (end.tv_nsec - start.tv_nsec) / 1000000;
  
          if (!rc || (rc &lt; 0)) return 0;
          recv += rc;
          timeout -= delta_ms;
  
          if (timeout &lt;= 0)
              return 0;
  
      } while (recv != count);
      return recv;
  }
  </code></pre>
  
  <p>On a serial port, poll returns on each single byte and causes many iterations.</p>
  
  <p><strong>Is there a more elegant way to solve that problem?</strong></p>
  
  <p>I am aware that depending on the baudrate, timeout might not decrement in that code portion. Counting nanoseconds might be a better approach.</p>