Putting limits on CPU and memory usage

In this section, we will learn about how we can limit CPU and memory usage. First, we will write a script for putting a limit on CPU usage. Create a script called put_cpu_limit.py and write the following code in it:

import resource
import sys
import signal
import time
def time_expired(n, stack):
print('EXPIRED :', time.ctime())
raise SystemExit('(time ran out)')
signal.signal(signal.SIGXCPU, time_expired)
# Adjust the CPU time limit
soft, hard = resource.getrlimit(resource.RLIMIT_CPU)
print('Soft limit starts as :', soft)
resource.setrlimit(resource.RLIMIT_CPU, (10, hard))
soft, hard = resource.getrlimit(resource.RLIMIT_CPU)
print('Soft limit changed to :', soft)
print()
# Consume some CPU time in a pointless exercise
print('Starting:', time.ctime())
for i in range(200000):
for i in range(200000):
v = i * i
# We should never make it this far
print('Exiting :', time.ctime())

Run the preceding script as follows:

$ python3 put_cpu_limit.py

Output:
Soft limit starts as : -1
Soft limit changed to : 10
Starting: Thu Sep 6 16:13:20 2018
EXPIRED : Thu Sep 6 16:13:31 2018
(time ran out)

In the preceding script, we used setrlimit() to limit the CPU usage. So, in our script, we have set the limit to 10 seconds.