I'm trying to understand how to put resource limits on a process from within that process in Mac OS X (I have 10.6). On CentOS, the following test program (python3.3) works as I expected it would:
import resource
import signal
def confirm(prompt, instructions='(y)es or (n)o only, please.'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no'):
return False
print(instructions)
def handle_cpu_soft_limit(signal, frame):
print('CPU soft limit reached.')
if not confirm('Do you want to continue anyway? (y/n): '):
raise ResourceWarning()
def long_function():
a = 0
while True:
a += 1
a -= 1
def main():
# set soft limit to 1 second, hard limit to 5 seconds (CPU time)
resource.setrlimit(resource.RLIMIT_CPU, (1, 5))
# set handler for soft CPU limit signal
signal.signal(signal.SIGXCPU, handle_cpu_soft_limit)
# do some busy work
try:
long_function()
except ResourceWarning:
print('Stopping now before being forced.')
if __name__ == '__main__':
main()
The program burns CPU time until the soft limit (1 second, the first element in the tuple passed to resource.setrlimit()) is reached. The program catches the signal sent by the OS (in this case, SIGXCPU) and asks me if I want to continue. On CentOS (or other linuxes), If I say yes, it will ask me again in one second intervals until the hard limit (5 seconds) is reached, at which point the OS kills the process. On Mac OS X, I still get and handle the SIGXCPU signal, but I never get the signal again, and the process is never killed, even when the hard limit is reached. This may or may not be related to what the asker of this question was experiencing.
The man page for setrlimit