使用subprocess.Popen的preexec_fn参数和resource模块。示例:
parent.py:
import os
import sys
import resource
import subprocess
def setlimits():
print "Setting resource limit in child (pid %d)" % os.getpid()
resource.setrlimit(resource.RLIMIT_CPU, (1, 1))
print "CPU limit of parent (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
p = subprocess.Popen(["./child.py"], preexec_fn=setlimits)
print "CPU limit of parent (pid %d) after startup of child" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
p.wait()
print "CPU limit of parent (pid %d) after child finished executing" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
child.py:
import os
import sys
import resource
print "CPU limit of child (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
parent.py会分叉出一个新进程。在新进程中,它将调用setlimits(),然后执行child.py。这意味着资源将在子进程中受到限制,但在父进程中不受限制。
运行程序时的输出:
./parent.py
CPU limit of parent (pid 17404) (-1, -1)
Setting resource limit in child (pid 17405)
CPU limit of parent (pid 17404) after startup of child (-1, -1)
CPU limit of child (pid 17405) (1, 1)
CPU limit of parent (pid 17404) after child finished executing (-1, -1)
在许多情况下,这比尝试使用ulimit更好,因为通过shell生成子进程并不总是一个好主意,特别是由于它经常会引起丑陋的参数引用问题。