如何在分支过程中处理套接字连接 [英] How is socket connection being handled in a forked process

查看:55
本文介绍了如何在分支过程中处理套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个充当TCP服务器的程序,该程序侦听端口5000.

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

现在,我想运行另一个与此服务器并行运行的命令行进程.我知道正确的方法是派生服务器,而不是调用"exec"....

Now I want to run another command-line process to run in parallel with this server. I know the right way to do it is to fork the server, than call "exec" ....

我的问题是,子进程是否也拥有"该端口5000?如果要释放此端口5000,是否需要同时杀死父进程和子进程?

My question is, is the child process also "owns" this port 5000? If I want to release this port 5000, do I need to kill both the parent process and the child process?

我只是很好奇这个分支连接是如何在分支中处理的.

I am just very curious how this socket connection is being handled in the forking.

推荐答案

  1. 首先,accept()传入连接.现在,接受过程具有侦听套接字和新接受的套接字的句柄.
  2. 叉和:
    • 在孩子中:
  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. 关闭监听套接字.
  2. 用可接受的插座做东西.

  • 在父级中:

  • In the parent:

    1. 关闭接受的套接字.
    2. 恢复接受循环.

  • 当关闭对句柄的所有引用时,将回收各种套接字资源.如果进程终止,则其所有句柄都将隐式关闭.因此,如果子级关闭其继承给侦听套接字的句柄,则该父级中剩余的唯一句柄存在.然后,当父级终止或显式关闭此句柄时,将回收监听套接字.

    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.

    这篇关于如何在分支过程中处理套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆