3

***Background**** I am new to TCP so I have question that may be a bit basic. I am trying to turn on O_NONBLOCK on a socket that is receiving data. Up until now I have tried to different ways to set O_NONBLOCK, itcl() and fcntl(). Right now I am trying to get fcntl() to work.

My Question: Are you supposed to set O_NONBLOCK before you connect the socket or after?

**my current implementation of fcntl() is based off off the link before the code:

How to reset a socket back to blocking mode (after I set it to nonblocking mode)?

//set socket to NONBlocking
on = fcntl(Socket,F_GETFL);
on = (on | O_NONBLOCK);
if(fcntl(Socket,F_SETFL,on) < 0)
    {
       perror("turning NONBLOCKING on failed\n");
    }

// DO CONNECT
rc = connect()

Thank you for taking the time to look at this

Community
  • 1
  • 1
WorkerBee
  • 683
  • 3
  • 11
  • 22

2 Answers2

6

You are supposed to set O_NONBLOCK whenever you want. If you do it before connect, then connect will be non-blocking as well (returning EINPROGRESS; you can select or poll for writable state to wait for its completion).

Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • is there a way to check and make sure it is on? – WorkerBee Jan 31 '13 at 20:08
  • do you want to check or to make sure it is on? anyway, that's what you already do with `F_GETFL` (you can insert "check" logic after `on = fcntl(...)`). – Anton Kovalenko Jan 31 '13 at 20:11
  • When I turn O_NONBLOCK on i get "Invalid argument" and "I/O error" (22, 5). Could turning on O_NONBLOCK mess up my connection? When I comment out `on = fcntl(Socket,F_GETFL);` and `on = (on | O_NONBLOCK);` it works. – WorkerBee Jan 31 '13 at 22:19
  • Where do you get those errors? Certainly not from `fcntl`? Can you provide a [complete example](http://sscce.org)? – Anton Kovalenko Jan 31 '13 at 22:50
0

And to answer part two, use the same code but turn the O_NONBLOCK bit off instead of on.

user207421
  • 305,947
  • 44
  • 307
  • 483