问题
I noticed something odd while working with a simple C-based server
program on my Linux (4.10.3) system. I accidentally ended up calling
listen()
twice on a socket (from the server process) I had
called bind()
on earlier. I noticed that both the listen calls
succeeded without any errors. In fact, it doesn't seem to matter how many
calls to listen I make, all calls to listen succeed.
I was expecting all the calls to listen after the first one to fail
with EADDRINUSE
. Am I missing something? Linux/POSIX man pages don't
seem to say anything about this. I did find one reference about
this behavior on the following web-page:
https://www.mkssoftware.com/docs/man3/listen.3.asp
An application may call listen() more than once on the same socket. This has the effect of updating the current backlog for the listening socket. Should there be more pending connections than the new backlog value, the excess pending connections are reset and dropped.
It's unclear to me if this also applies to Linux. And so my question is: what happens when listen is called on the same socket more than once from the same process? (Apparently there are no visible side-effects in user space, but does the Linux kernel do something special in kernel space?)
Thanks.
回答1:
The Linux kernel adjusts the backlog queue length using the new backlog value, but only for future connection requests. It does not discard any pending connections already in the queue.
Second and subsequent calls to listen()
have no other effect, and will not fail unless the socket is of the wrong type (not SOCK_STREAM
), or is in the wrong state (already connected to a specific peer, or is already in the process of being closed).
来源:https://stackoverflow.com/questions/43078649/listen-called-on-socket-more-than-once-expected-behavior