select() returns invalid argument select() returns invalid argument unix unix

select() returns invalid argument


To absolutely guarantee that the read will never block, you must set O_NONBLOCK on the fd.

Your select error is almost certainly caused because you aren't setting the entire time struct. You're only setting the seconds. The other field will contain garbage data picked up from the stack.

Use struct initialization. That will guarantee the other fields are set to 0.

It would look like this:

struct timeval timeout = {1, 0};

Also, in your select loop you should be aware that Linux will write the time remaining into the timeout value. That means that it will not be 1 second the next time through the loop unless you reset the value to 1 second.


According to the manpage:

On error, -1 is returned, and errno is set appropriately; the sets and timeout become undefined, so do not rely on their contents after an error.

You are not checking the return code from select().

The most likely explanation is that select() is being interrupted (errno=EINTR) and so returning an error, and the FD bit is still set in the "read" fd_set giving you the behaviour you are seeing.

Incidentally it is a very bad idea to name variables after standard/system/common functions. "read_fds" would be a MUCH better name than "read".


It's correct. See the select() manpage in Linux for example: http://linux.die.net/man/2/select

"Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks"

The only solution is to use NON-BLOCKING socket.