我在基于 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/