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

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

问题描述

例如,我有一个程序用作 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天全站免登陆