Say that I call select() on a FD_SET containing a bunch of read file descriptors. What happens if during the select() call, one of the file descriptor closes? Assuming that some sort of error occurs, then is it my responsibility to find and remove the closed file descriptor from the set?
Share
I don’t believe this is specified anywhere; some systems may immediately return from
selectwhile others may continue blocking. Note that the only way this can happen is in a multi-threaded process (otherwise, theclosecannot happen duringselect; even if it happened from a signal handler,selectwould have already been interrupted by the signal). As such, this situation arising probably indicates you have bigger issues to worry about. If one of the file descriptors you’re polling can be closed duringselect, the bigger issue is that the same file descriptor might be reassigned to a newly opened file (e.g. one opened in another unrelated thread) immediately after theclose, and the thread that’s polling might then wrongly perform IO on the new file “belonging to” a different thread.If you have a data object that consists of a set of file descriptors that will be polled with
selectin a multithreaded program, you almost surely need to be using some sort of synchronization primitive to control access to that set, and adding or removing file descriptors should require a lock that’s mutually exclusive with the possibility thatselect(or any IO on the members) is in progress.Of course in a multi-threaded program, it may be better not to use
selectat all and instead let blocking IO in multiple threads achieve the desired result without complicated locking logic.