In most
applications, you do not have to worry about cleaning up your sockets.
When you exit your program and your process terminates, the sockets
are closed for you. If you need to close a socket while your program
is still running, use the close
system call.
For example, you may have a daemon process that uses fork
to create the server process. The daemon process creates the BSD
sockets connection and then passes the socket descriptor to the
server. You then have more than one process with the same socket
descriptor. The daemon process should do a close
of the socket descriptor to avoid keeping the socket open once the
server is through with it. Because the server performs the work,
the daemon does not use the socket after the fork.
close decrements the file
descriptor reference count. Once this occurs, the calling process
can no longer use that file descriptor.
When the last close is executed
on a socket descriptor, any unsent data are sent before the socket
is closed. Any unreceived data are lost. This delay in closing the
socket can be controlled by the socket option SO_LINGER. Additional options for
closing sockets are discussed in chapter 3, "Advanced Topics
for Stream Sockets."
For syntax and details on close,
refer to the close(2) man page.