13.14 我们相对运行的程序占用的CPU和内存设定一个限制
import signal
import resource
import os
def time_exceeded(signo,frame):
print("Times UP")
raise SystemExit(1)
def set_max_runtime(seconds):
soft,hard =resource.getrlimit(resource.RLIMIT_CPU)
resource.setrlimit(resource.RLIMIT_CPU,(seconds,hard))
signal.signal(signal.SIGXCPU,time_exceeded)
def __name__ == '__main__':
set_max_runtime(15)
while True:
pass
- 运行上述代码时,当超时时会产生SIGXCPU信号,程序会自动清理退出。
- 要想限制内存使用,可以使用总地址空间上设定一个限制
def limit_memory(maxsize):
soft,hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(resource.RLIMIT_AS,(maxsize,hard))
- 当达到设定的内存限制后,如果没有更多的内存可以使用,程序会产生MemoryError异常
网友评论