Linux – Should sockets be set to non-blocking before being polled by select()?

Should sockets be set to non-blocking before being polled by select()?… here is a solution to the problem.

Should sockets be set to non-blocking before being polled by select()?

I REMEMBER THAT WHEN WE WANTED TO USE SELECT() ON A SOCKET DESCRIPTOR, THAT SOCKET SHOULD BE SET TO NONBLOCKING IN ADVANCE.

But today, I read a source file where there doesn’t seem to be a line with socket set to non-blocking
Is my memory right?

Thanks!

Solution

Duskwuff is right

In general, you do not need to set a socket as non-blocking to use it
in select().

True if your kernel is POSIX compliant in terms of select(). Unfortunately, some people use Linux, but this is not the case, as the Linux select() man page says:

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.

This was discussed on or

around Saturday, June 18, 2011 on LKML. A kernel hacker tries to prove POSIX non-compliance. They respect POSIX when it’s convenient and desecrate it when it’s inconvenient.

He argued that “there could be two readers, and the second would block.” “But such an application flaw is unreasonable. The kernel is not expected to prevent application defects. The kernel has a clear responsibility: in all cases of the first read() after select(), the kernel must return at least 1 byte, EOF, or error; But never stop. As for write(), you should always test whether select() reports that the socket is writable before writing. This guarantees that you can write at least one byte or an error will occur; But never stop. Let select() do it for you, don’t blindly write in the hope you won’t block. Linux hackers’ tips for extreme cases and the like are euphemisms for “we’re too lazy to solve difficult problems.”

Suppose you read a serial port set:

min N; with -icanon, set N characters minimum for a completed read

time N; with -icanon, set read timeout of N tenths of a second

min 250 time 1

Here you need a block of 250 characters, or a tenth-second timeout. When I try this in non-blocking mode on Linux, reading every character is returned, which affects the CPU. It must be put into blocking mode to get the recorded behavior.

So there are good reasons to use blocking mode with select() and expect your kernel to be POSIX compliant.

But if you have to use Linux, Jeremy’s advice might help you deal with some of the pitfalls of its kernel.

Related Problems and Solutions