Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use the preexec_fn parameter to subprocess.Popen, and the resource module. Example:</p> <p><em>parent.py:</em></p> <pre><code>#!/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) </code></pre> <p><em>child.py:</em></p> <pre><code>#!/usr/bin/env python import os import sys import resource print "CPU limit of child (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU) </code></pre> <p><em>parent.py</em> will fork into a new process. In the new process, it will call setlimits(), then exec <em>child.py</em>. This means the resource will be limited in the child process, but not in the parent.</p> <p>Output when running program:</p> <pre><code>./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) </code></pre> <p>This is in many cases a better solution than trying to use ulimit, since it's not always a good idea to spawn subprocess via shell, especially since it often causes ugly parameter quoting trouble.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload