我在用multiprocessing.Pool.map
,它分叉当前进程。
我的理解是,默认情况下,所有文件描述符包括插座分叉时从主进程复制。主进程本身是一个Web服务器(使用cherrypy http://cherrypy.org/),所以这会对开放端口等造成严重破坏。分叉进程实际上只做了一些事情CPU 密集型数字内容 https://stackoverflow.com/questions/9964809/numpy-vs-multiprocessing-and-mmap在服务器正在使用的库之一内——与网络/套接字部分无关。
有没有一种简单的方法可以自动关闭新进程中的所有套接字?或者避免分叉 CherryPy 服务器出现问题的另一种方法?
使用 CherryPy 3.2.2、Python 2.7;必须在 Linux 和 OS X 上运行。
POSIX 不包括列出或关闭一系列文件描述符的合理方法。
因此,我们必须遍历整个范围(例如从 3 到 1023),一次关闭一个文件描述符。
或者,如果我们有 /proc 文件系统,我们可以读取 /proc/self/fd 中打开的文件描述符列表并关闭它们。这比关闭所有可能的文件描述符要快。
import os
def close_files(fd_min=3, fd_max=-1):
if os.path.exists('/proc/self/fd'):
close_files_with_procfs(fd_min, fd_max)
else:
close_files_exhaustively(fd_min, fd_max)
def close_files_exhaustively(fd_min=3, fd_max=-1):
import resource
fd_top = resource.getrlimit(resource.RLIMIT_NOFILE)[1] - 1
if fd_max == -1 or fd_max > fd_top:
fd_max = fd_top
for fd in range(fd_min, fd_max+1):
try:
os.close(fd)
except OSError:
pass
def close_files_with_procfs(fd_min=3, fd_max=-1):
for nm in os.listdir("/proc/self/fd"):
if nm.startswith('.'):
continue
fd = int(nm)
if fd >= fd_min and (fd_max == -1 or fd < fd_max):
try:
os.close(fd)
except OSError:
pass
def timereps(reps, func):
from time import time
start = time()
for i in range(0, reps):
func()
end = time()
return (end - start) / reps
print "close_files: %f" % timereps(100, lambda: close_files())
print "close_files_exhaustively: %f" % timereps(100, lambda: close_files_exhaustively())
print "close_files_with_procfs: %f" % timereps(1000, lambda: close_files_with_procfs())
在我的系统上:
$ python ./close_fds.py
close_files: 0.000094
close_files_exhaustively: 0.010151
close_files_with_procfs: 0.000039
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)