- First,
accept()
the incoming connection. The accepting process now has a handle to the listening socket, and the newly accepted socket. - Fork and:
- In the child:
- Close the listening socket.
- Do stuff with the accepted socket.
- In the parent:
- Close the accepted socket.
- Resume the accept loop.
- In the child:
The various socket resources will be reclaimed when all references to the handle are closed. If a process terminates, all its handles are closed implicitly. Therefore if a child closes the handle it inherits to the listening socket, the only handle remaining to that socket exists in the parent. Then the listening socket will be reclaimed when the parent terminates, or closes this handle explicitly.