(原谅我的英语不好,我不是母语)
我尝试使用 Python 资源模块来限制子进程。
似乎设置RLIMIT_CPU可以成功限制cputime的数量,但是其他的如RLIMIT_RSS根本不起作用。
例如,我使用以下脚本调用child.py,并将RSS限制设置为(1024, 1024):
import os
import sys
import resource
import subprocess
def setlimits():
resource.setrlimit(resource.RLIMIT_RSS, (1024, 1024))
p = subprocess.Popen(["./child.py"], preexec_fn=setlimits)
print(p.wait())
child .py:
#!/usr/bin/env python3
import resource
print("RSS limit: ", resource.getrlimit(resource.RLIMIT_RSS))
a=[]
while True:
a.append(1) # deadloop, until eat up memory
子进程打印“RSS limit: (1024, 1024)”然后继续运行直到被杀死。 我可以看到 child.py 正在吞噬我的内存,但 RLIMIT_RSS 不起作用。
我的操作系统是最新的 Archlinux(2.6.39 内核),Python 是 ver3.2。
最佳答案
根据 setrlimit() 的文档, RLIMIT_RSS
在 Linux 2.4.30 及更高版本中无效。此外,它只计算标有 madvise() 的内存:
RLIMIT_RSS
Specifies the limit (in pages) of the process's resident set (the number of virtual pages resident in RAM). This limit only has effect in Linux 2.4.x, x < 30, and there only affects calls tomadvise()
specifyingMADV_WILLNEED
.
因此,如果您真的想以这种方式限制进程,则必须运行 2.4 内核并破解 Python 解释器,以便它在分配的内存上调用 madvise()
,这可能有意想不到的副作用。
关于Python 资源模块不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6556442/