如何在python中设置线程或进程的内存限制?
我正在用Python编写程序,该程序将能够在某种沙箱中运行不受信任的python代码.因此,我需要一种方法来限制不受信任的代码可以分配的内存量.现在,我可以通过覆盖沙盒环境中的默认python数据结构来限制range(),列表,字典和其他对象的最大长度.
I'm writing program in Python which would be able to run untrusted python code in some kind of sandbox. So, I need a way to limit the amount of memory that untrusted code can allocate. At now I can limit the maximum length of range(), list, dictionary and the others by overriding default python data structures in my sandboxed environment.
有什么想法吗?
在Unix下,您可以使用 resource.setrlimit(resource.RLIMIT_AS,...)进行限制 进程可能占用的地址空间的最大区域(以字节为单位)."
Under Unix, you could use resource.setrlimit(resource.RLIMIT_AS, ...) to restrict "the maximum area (in bytes) of address space which may be taken by the process."
import sys
import resource
soft, hard = 10**7, 10**7
# soft, hard = 10**8, 10**8 # uncommenting this allows program to finish
resource.setrlimit(resource.RLIMIT_AS,(soft, hard))
memory_hog = {}
try:
for x in range(10000):
print(x)
memory_hog[str(x)]='The sky is so blue'
except MemoryError as err:
sys.exit('memory exceeded')
# memory exceeded