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

python使用套接字打开所有文件描述符,python,sockets,flask,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

我在基于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打开的文件描述符引起的。为了防止这个问题,我尝试访问套接字的所有文件描述符。如何才能做到这一点?

为解决此问题,可用于获取所有正在创建的对象。创建并绑定socket后,可以运行此代码并获取所有SocketObject

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)

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

在这种情况下,应使用close_fds=True调用Popen。

python3.8的完整解决方案

def\u启动时运行(字符串):
导入套接字,fcntl
对于插入式筛选器(lambda x:type(x)=socket.socket,gc.get_objects()):
fd=sock.fileno()
旧标志=fcntl.fcntl(fd,fcntl.F_GETFD)
fcntl.fcntl(fd,fcntl.F_SETFD,old_flags | fcntl.fd_CLOEXEC)
@首次请求前的应用程序(启动时运行)

fcntl特定于UNIX,在Windows上不可用。Windows有什么解决方法吗?在python3.8中,我得到了AttributeError:模块“socket”没有属性“\u socketobject”