I have a situation where a thread is selecting on sockets that are managed by a separate thread.
When a socket is closed, select() presumably returns that socket as “available”, and it isn’t until I try to read from it that I realize that it is closed.
But I’m seeing a paradox: when the socket is closed from the other thread, the system is free to reallocate its file descriptor for other purposes. (I think.)
How can I be guaranteed that by the time I read from the socket (just a numeric descriptor) the system hasn’t already recycled that descriptor and used it for a new socket? In other words, for all I know I might be reading from some other socket that has been recently opened (perhaps a socket I shouldn’t even be including in my select()!) instead of the just-closed socket.
I could keep a list of recently closed descriptors, but I’m wondering if there is a better way.
The short answer: Don’t close sockets from another thread, that you’re reading from in this one!
The FD could, potentially, be reassigned. But you will have problems if you’re reading from one FD in multiple threads without some kind of scheme to communicate between them. Now, if you have a “Socket description” structure in shared memory that has a control semaphore and some indications of the FD, and other status information, maybe that could be manageable, but I think you’ll discover that the simplest solution is almost always to make FD’s specific to a single thread…