3

Shoud I make file descriptors non-blocking before using them in select()?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111

3 Answers3

6

Doesn't matter.

select tells you which sockets are readable/writable/closed/have state that you're interested in. Blocking/non-blocking affects how e.g. a recv or send call acts. These are independent of each other.

Erik
  • 88,732
  • 13
  • 198
  • 189
  • Same thing - read/write is affected by O_NONBLOCK, select doesn't care about blocking or not. – Erik Apr 05 '11 at 16:06
  • "Doesn't matter" is 100% correct in theory, but in practice you should still make descriptors nonblocking, because on some systems (e.g. Linux) recv may still block, even though readiness has been reported. The exemplary case given in the documentation is a network packet being discarded due to having an incorrect checksum after readiness has been signalled. – Damon Apr 05 '11 at 17:20
  • @Damon: I though so too, but thankfully that bug was later fixed, despite originally being flagged WONTFIX. However, it's still important to have any file descriptors you'll be **writing** to set `O_NONBLOCK`, because otherwise an attempt to write more than the remaining free buffer space will block rather than returning a short write. – R.. GitHub STOP HELPING ICE Apr 05 '11 at 17:27
  • @R: it's also necessary to have sockets you'll `accept()` from non-blocking as the client connection attempt may be discarded between the `select()` call and the `accept()` call. – Tony Delroy Apr 06 '11 at 08:58
  • @Mihran Hovsepyan: the same applies to all kinds of file descriptors. Pipes, TTYs, character devices, anything. – Serge Dundich Apr 06 '11 at 20:05
3

Select itself will block regardless of the blocking status of the descriptors it is used to monitor. If you don't want select to block, use a timeout of 0 (i.e. point to a timeval structure of zero, not a nil pointer).

jbruni
  • 1,238
  • 8
  • 12
0

The goal of select is to block, so it will ignore the non blocking flag. However, as described in the bugs section in the Linux manual pages:

Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.

So, due to buggy behavior, you should set the file descriptors to non-blocking.

tshepang
  • 12,111
  • 21
  • 91
  • 136
hdante
  • 7,685
  • 3
  • 31
  • 36