How does accept( ) determine which integer to return?
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( )
cal开发者_StackOverflowls, 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).
The short answer is, do NOT count on accept giving you integers in any expected order. No matter how seductively easy you think it would make things if it did.
What accept is returning is actually a 'descriptor' to a kernel resource that will connect that descriptor to the proper drivers necessary to read and write, close, seek(if capable). The pool of available descriptors is limited, so when you close a socket its descriptor goes back into the pool and can be reused.
It's returning a file descriptor for the accepted socket:
RETURN VALUES
The call returns -1 on error and the global variable errno is set to
indicate the error. If it succeeds, it returns a non-negative integer
that is a descriptor for the accepted socket.
This gives you a numeric value that What value that you can use with various file operations, and is decided behind the scenes.
精彩评论