Using the C sockets library on a Linux system…
When I make a call to accept( ) it always returns an integer. STDIN is 0. Usually my first accept call returns 3. They increment after that.
I was wondering; how does accept( ) determine which integer is next? If, after 2 more accept( ) calls, I have 3, 4, and 5 assigned to connected clients; what happens when 4 disconnects? Is the next integer 4 or is it 6?
If someone could shed some light on this I sure would appreciate it.
It uses the next currently unopen file descriptor, the same as
open()and other system calls that return file descriptors;dup2()is something of an exception to the pattern.(A file descriptor might not be open but might still be unavailable for reuse if it was part of a network connection that has not been completely cleaned up yet, for example.)(Update: struck out text reinstates original version of answer. If a file descriptor is closed, it is available for reuse. There might be issues with reusing a socket address because of FIN-WAIT states in TCP/IP – but a socket address is not the file descriptor.)If you have descriptors 1-5 open, then close 4, the next open-like operation will return 4.
There might be security-conscious systems where this is not the pattern, but it is unlikely. One reason is that there is correct code for handling I/O redirection that relies on closing standard input (file descriptor 0) and the next open-like operation reusing the file descriptor; repeat for standard output (file descriptor 1).