Python 资源模块不起作用

标签 python linux

(原谅我的英语不好,我不是母语)

我尝试使用 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 to madvise() specifying MADV_WILLNEED.

因此,如果您真的想以这种方式限制进程,则必须运行 2.4 内核并破解 Python 解释器,以便它在分配的内存上调用 madvise(),这可能有意想不到的副作用。

关于Python 资源模块不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6556442/

相关文章:

python - 为什么这个元素不可见(Selenium + Python/Django 1.9)

python - Python 中 float 的余数

python - 在 Django 中看不到迁移列表

php - exec() 通过命令行而不是网络运行

ruby - 如何锁定 ruby 中fork共享的IO

linux - 我无法克隆 git 树

linux - 如何使用 gstreamer 将 AAC 音频 mp4 转换为 mp3

linux - Shell 命令循环变量并打印到文件

python - Web.py 中的子应用总是返回 405

python - 具有标称或有序轴类型的 Bokeh 图