W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
You want to place some limits on the memory or CPU use of a program running onUnix system.
The resource module can be used to perform both tasks. For example, to restrict CPUtime, do the following:
import signalimport resourceimport os
def time_exceeded(signo, frame):print(“Time's up!”)raise SystemExit(1)def set_max_runtime(seconds):# Install the signal handler and set a resource limitsoft, hard = resource.getrlimit(resource.RLIMIT_CPU)resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard))signal.signal(signal.SIGXCPU, time_exceeded)if name == ‘main':
set_max_runtime(15)while True:
pass
When this runs, the SIGXCPU signal is generated when the time expires. The programcan then clean up and exit.To restrict memory use, put a limit on the total address space in use. For example:
import resource
def limit_memory(maxsize):soft, hard = resource.getrlimit(resource.RLIMIT_AS)resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))
With a memory limit in place, programs will start generating MemoryError exceptionswhen no more memory is available.
In this recipe, the setrlimit() function is used to set a soft and hard limit on a particularresource. The soft limit is a value upon which the operating system will typically restrictor notify the process via a signal. The hard limit represents an upper bound on the valuesthat 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 cannever 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 thenumber of child processes, number of open files, and similar system resources. Consultthe 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 allof them. For example, when tested, it works on Linux but not on OS X.
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: