python 获取所有使用套接字打开的文件描述符

标签 python sockets flask

我在基于 UNIX 的操作系统上使用 Flask 和 Flask 的内部 Web 服务器。我运行它就像;

APP.run(host='', port=8000, threaded=True, debug=False)

我在代码中重新启动了一些服务,例如

  for service in ACTIVE_SERVICES:
        command = "/etc/init.d/%s restart" % service
        # stdout and stderr are string which output of command
        stdout, stderr = Popen(command, stdout=PIPE, stderr=PIPE,shell=True).communicate()

当我停止 Flask 应用程序时,我重新启动的其他服务开始监听 8000 端口。这是由子进程继承的flask打开文件描述符引起的。为了防止这个问题,我尝试访问套接字的所有文件描述符。怎么才能做到这一点?

最佳答案

为了解决这个问题,gc可用于获取所有创建对象。创建并绑定(bind)套接字后,您可以运行此代码并获取所有套接字对象;

for sock in filter(lambda x: type(x) == socket._socketobject, gc.get_objects()):
    fd = sock.fileno()
    old_flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    fcntl.fcntl(fd, fcntl.F_SETFD, old_flags | fcntl.FD_CLOEXEC)

此代码阻止继承套接字的文件描述符。

关于python 获取所有使用套接字打开的文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23709926/

相关文章:

python - 运行AWS Deep Learning Base AMI(Amazon Linux 2)时如何在Elastic Beanstalk中设置WSGI?

python - 异步和异步错误——TypeError : 'coroutine' object is not callable

python - 使用切片将字符串拆分为单个字符

python - 无法让 Django 网址工作

iOS Swift SSL 套接字自签名证书

c - TCP 服务器在 ubuntu 14.04 上使用错误的端口号

python - Celery 后台任务出现 "Working outside of request context"错误

python - 在列表中找到四个数字加起来等于目标值

python - 将 SDF 添加到管道,而无需传递虚拟输入

c - 发送文件(客户端到服务器和服务器到客户端)