Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a non-blocking socket connection in C

Tags:

c

sockets

I'm changing a socket connection in a script to a non-blocking connection. In a tutorial I found the lines:

x=fcntl(s,F_GETFL,0);              // Get socket flags
fcntl(s,F_SETFL,x | O_NONBLOCK);   // Add non-blocking flag

So I added them after I create my socket and before the connect statement. And it's no longer blocking :) but it also doesn't connect. I'm not getting any errors, the connect is just returning -1. If I comment these lines out it connects.

What else do I need to add to get a non-blocking connection to connect?

like image 481
Bill Avatar asked Sep 27 '12 15:09

Bill


People also ask

What is non-blocking socket in C?

We set a flag on a socket which marks that socket as non-blocking. This means that, when performing calls on that socket (such as read and write ), if the call cannot complete, then instead it will fail with an error like EWOULDBLOCK or EAGAIN . To mark a socket as non-blocking, we use the fcntl system call.

Is socket () a blocking system call?

The default mode of socket calls is blocking. A blocking call does not return to your program until the event you requested has been completed.

Is listen () a blocking call?

listen() is non-blocking.


1 Answers

Check return value of connect(2) - you should be getting -1, and EINPROGRESS in errno(3). Then add socket file descriptor to a poll set, and wait on it with select(2) or poll(2).

This way you can have multiple connection attempts going on at the same time (that's how e.g. browsers do it) and be able to have tighter timeouts.

like image 50
Nikolai Fetissov Avatar answered Sep 28 '22 01:09

Nikolai Fetissov