How is socket connection being handled in a forked process

后端 未结 2 689
闹比i
闹比i 2020-12-23 12:01

I have a program that serves as a TCP server that listens to port 5000, for example.

Now I want to run another command-line process to run in parallel with this ser

2条回答
  •  时光说笑
    2020-12-23 12:25

    1. First, accept() the incoming connection. The accepting process now has a handle to the listening socket, and the newly accepted socket.
    2. Fork and:
      • In the child:
        1. Close the listening socket.
        2. Do stuff with the accepted socket.
      • In the parent:
        1. Close the accepted socket.
        2. Resume the accept loop.

    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.

提交回复
热议问题