0

if a socket is set non-blocking,

but at a certain moment, I want to use send or recv with this socket in blocking mode,

can I temporarily sent it as blocking mode and then recover to non-blocking.

if so, how about the other way around? use send or recv temporarily in non-blocking mode if the socket is in blocking mode?

thanks!

misteryes
  • 2,167
  • 4
  • 32
  • 58

4 Answers4

3

You can use fcntl() with the O_NONBLOCK flag.

Use it to set the socket the blocking mode, send(or recv) your data and use fcntl again to set to the socket the non-blocking mode.

nouney
  • 4,363
  • 19
  • 31
2

can I temporarily sent it as blocking mode and then recover to non-blocking.

Yes, of course, just use FIONBIO the other way round.

if so, how about the other way around? use send or recv temporarily in non-blocking mode if the socket is in blocking mode?

Yes, of course. There are two ways to do that: with FIONBIO or with the MSG_DONTWAIT flag to recv().

user207421
  • 305,947
  • 44
  • 307
  • 483
  • @misteryes Look at [this question](http://stackoverflow.com/questions/1150635/unix-nonblocking-i-o-o-nonblock-vs-fionbio) about FIONBIO and O_NONBLOCK – nouney Jun 14 '13 at 12:07
  • 1
    I don't get it when you say FIONBIO can set a non-blocking socket temporarily to blocking mode. – misteryes Jun 14 '13 at 12:09
  • It's not temporarily with FIONBIO, it acts like O_NONBLOCK. that means you have to call `ioctl()` before and after the `recv()`/`send()`, just like `fcntl()` (which is a POSIX function, so you should use it instead of `ioctl()`) – nouney Jun 14 '13 at 12:40
  • I don't see what there is not to get. FIONBIO is used to set or clear non-blocking mode. Or O_NONBLOCK. – user207421 Jun 14 '13 at 20:04
1

You could change the mode, or you could just use select() or epoll() to detect when a socket is readable/writable before performing a recv/send() that would normally block, or to simulate blocking behavior by reading/sending in a loop while the intended data is still pending.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

Well, as already has been said, you can of course change the state whenever you want with the fcntl() call. However I don't really understand the requirement, because when you implement a non blocking algorithm, you can of course make it appear as if it were blocking by simply looping. And you will need a protocoll anyway, so this seems to me as if you were relying on some particular behaviour.

Devolus
  • 21,661
  • 13
  • 66
  • 113