tags:

views:

581

answers:

6

Please tell mw how to convert a TCP IP socket into NON Blocking socket. I am aware of the fcntl() function but I heard that they are not always reliable.

+8  A: 

What do you mean by "not always reliable"? If the system succeeds in setting your socket non non-blocking, it will be non-blocking. Socket operations will return EWOULDBLOCK if they would block need to block (e.g. if the output buffer is full and you're calling send/write too often).

This forum thread has a few good points when working with non-blocking calls.

unwind
+3  A: 

fcntl() or ioctl() are used to set the properties for file streams. When you use this function to make a socket non-blocking, function like accept(), recv() and etc, which are blocking in nature will return error and errno would be set to EWOULDBLOCK. You can poll file descriptor sets to poll on sockets.

Siva
Is there any other way of converting a TCPIP to NON BLOCKING socket. I dont want to rely on these methods may be because of my past experiences
Sachin Chourasiya
That **is** the way to convert a socket to non-blocking. If you can be specific on your "past experiences" and why you are convinced that this won't work, maybe we can help you.
Graeme Perrow
A: 

The best method for setting a socket as non-blocking in C is to use ioctl. An example where an accepted socket is set to non-blocking is following:

long on = 1L;
unsigned int len;
struct sockaddr_storage remoteAddress;
len = sizeof(remoteAddress);
int socket = accept(listenSocket, (struct sockaddr *)&remoteAddress, &len)
if (ioctl(socket, (int)FIONBIO, (char *)&on))
{
    printf("ioctl FIONBIO call failed\n");
}
Steve Wranovsky
A: 

Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2), poll(2) or some other system calls available on your system.

See The C10K problem for the comparison of approaches to scalable IO multiplexing.

Andrey Vlasovskikh
A: 

Can you use setsockopt()?

codymanix
A: 

fcntl() has always worked reliably for me. In any case, here the function I use to enable/disable blocking on a socket:

/** Returns true on success, or false if there was an error */
bool SetSocketBlockingEnabled(int fd, bool blocking)
{
   if (fd < 0) return false;

#ifdef WIN32
   unsigned long mode = blocking ? 0 : 1;
   return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false;
#else
  int flags = fcntl(fd, F_GETFL, 0);
  if (flags < 0) return false;
  flags = blocking ? (flags&~O_NONBLOCK) : (flags|O_NONBLOCK);
  return (fcntl(fd, F_SETFL, flags) == 0) ? true : false;
#endif
}
Jeremy Friesner