Monday, May 11, 2009

[TIP] Non Blocking C Read

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_SET(fd, &rfds);

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

if (select(1, &rfds, NULL, NULL, &tv) <= 0)

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

No comments:

Post a Comment