6

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?

2 Answers 2

6

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.

4

connect will probably immediately return a EINPROGRESS error. Read up on use of select.

Note that you'll probably want to wrap your call to select in the TEMP_FAILURE_RETRY macro.

2
  • Hmm, what's the point here? How is it different from blocking connect? Commented Sep 27, 2012 at 15:48
  • @NikolaiNFetissov Fair point, I've edited my answer to remove the code snippet as potentially misleading and emphasise use of TEMP_FAILURE_RETRY
    – simonc
    Commented Sep 27, 2012 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.