Using UNIX Domain Stream Sockets
Closing a Socket
Closing a Socket
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 and 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.
Chapter 6
139