[TIP] Non Blocking C Read

May 11, 2009 Matteo Bertozzi | Filed Under Tips | No Comments

This is Just a simple code that maybe all the Linux C Developer knows, but if someone is still learning, This is a function that wrap the standard read function adding the non blocking feature. It’s Really useful in relation with Sockets.

int nonblock_read (int fd, char *buffer, size_t bufsize, int timeout) {
  if (timeout > 0) {
    struct timeval tv;
    fd_set rfds;

    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);

    tv.tv_sec = 0;
    tv.tv_usec = timeout * 1000;

    if (select(1, &rfds, NULL, NULL, &tv) <= 0)
      return(-ETIME);
  }

  return(read(fd, buffer, bufsize));
}

No Comments yet »

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>