Sometimes it is needed to make a socket non-blocking so that I/O requests on the socket don’t block. For a non-blocking socket, when I/O requests like read() and write() return a negative value, the errno should be checked against -EWOULDBLOCK code to find if the I/O request would have blocked.

The following utility function sets non-blocking flag of a socket.

int socketSetNonBlocking(int sockfd)
{
  unsigned int flags;

  flags = fcntl(sockfd. F_GETFL, 0);
  if(flags < 0) return -1;
  if(fcntl(sockfd, F_SETFL, flags|O_NONBLOCK) < 0) return -1;
  return 0;
}

Similarly the following function makes a non-blocking socket a blocking socket.

int socketSetBlocking(int sockfd)
{
  unsigned int flags;

  flags = fcntl(sockfd. F_GETFL, 0);
  if(flags < 0) return -1;
  if(fcntl(sockfd, F_SETFL, flags & ~O_NONBLOCK) < 0) return -1;
  return 0;
}

The following is the way to find if an I/O request is going to block after making a socket non-blocking.

rval = recv(sockfd, buf, 1024, 0);
if(rval < 0) {
  if(errno == -EWOULDBLOCK) {
     /* Not a socket error. the recv call would have blocked the program.
    do any other work here and try again */
  }
}

You can use similar coding for other blocking system calls like write(), readfrom(), sendto().
For connect() call, errno will be set to EINPROGRESS to indicate that connection establishment is in progress.