Sử dụng tham số preexec_fn để subprocess.Popen và mô-đun tài nguyên. Ví dụ:
parent.py:
#!/usr/bin/env python
import os
import sys
import resource
import subprocess
def setlimits():
# Set maximum CPU time to 1 second in child process, after fork() but before exec()
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:
#!/usr/bin/env python
import os
import sys
import resource
print "CPU limit of child (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
parent.py sẽ phân nhánh thành một quá trình mới. Trong quá trình mới, nó sẽ gọi setlimits(), sau đó thực hiện child.py. Điều này có nghĩa là tài nguyên sẽ bị giới hạn trong tiến trình con, nhưng không bị giới hạn trong phụ huynh.
Output chương trình khi chạy:
./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)
Đây là trong nhiều trường hợp là một giải pháp tốt hơn so với cố gắng sử dụng ulimit, vì nó không phải luôn luôn là một ý tưởng tốt để đẻ trứng subprocess qua vỏ, đặc biệt là kể từ khi nó thường gây tham số xấu xí trích dẫn sự cố.
Nguồn
2009-11-06 19:59:22
Bạn có thể muốn chấp nhận câu trả lời được bỏ phiếu cao nhất thay vì câu trả lời của tôi. Nó tốt hơn tôi nhiều. –