发布于 2015-08-30 08:01:34 | 277 次阅读 | 评论: 0 | 来源: 网络整理
The resource module can be used to perform both tasks. For example, to restrict CPU time, do the following:
import signal import resource import os
set_max_runtime(15) while True:
pass
When this runs, the SIGXCPU signal is generated when the time expires. The program can then clean up and exit. To restrict memory use, put a limit on the total address space in use. For example:
import resource
With a memory limit in place, programs will start generating MemoryError exceptions when no more memory is available.
In this recipe, the setrlimit() function is used to set a soft and hard limit on a particular resource. The soft limit is a value upon which the operating system will typically restrict or notify the process via a signal. The hard limit represents an upper bound on the values that may be used for the soft limit. Typically, this is controlled by a system-wide pa‐ rameter set by the system administrator. Although the hard limit can be lowered, it can never be raised by user processes (even if the process lowered itself). The setrlimit() function can additionally be used to set limits on things such as the number of child processes, number of open files, and similar system resources. Consult the documentation for the resource module for further details. Be aware that this recipe only works on Unix systems, and that it might not work on all of them. For example, when tested, it works on Linux but not on OS X.