Bob Miller wrote: >Ben Barrett wrote: > >>When a process starts that uses a port, say apache httpd, and then it >>bombs out badly or quits unexpectedly, how can one recover the locked >>port(s)? >> > >The kernel cleans up automatically. When the process exits >(voluntarily or not), the kernel closes all its descriptors. > >For TCP sockets, that means shutting down the connection. > Another note on this, FYI...
When a TCP socket is closed, either by a program explictly with close() or by the kernel if it is cleaning up, it doesn't get completely shut down. Instead it gets put into a TIME_WAIT state. You may see this state if you run netstat after a program exits. The purpose of TIME_WAIT is to allow for any stray or slow network data to fizz out, and for security purposes so this old data does not get associated with new streams. When a socket is in TIME_WAIT mode, a new server process will not be able to bind itself to the port as it is still somewhat in use. There is a socket option, SO_REUSEADDR, that will change this behavior and allow a new socket to be bound. I think most server programs use this option, because the TIME_WAIT period can last a few minutes. Its a pain to have to wait that long when you want to, for example, change a configuration setting and restart a service, or if a service crashes and needs to be restarted. However, although convenient it makes things a little less correct and reliable in terms of how TCP is supposed to work. If you ever have a problem with a server process that won't start up right away after it's been shut down, it probably doesn't enable the SO_REUSEADDR option... Kahli
