Use rlimit to add soft and hard resource limits on subprocesses you create

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

The following code will exit 1 second after starting, thanks to rlimit_cpu: 1

pid = Process.spawn "./heavy_cpu.rb", rlimit_cpu: 1
Process.waitpid pid

This next one limits memory (rlimit_as - addressable space) to 2**28 bytes.

pid = Process.spawn "./heavy_ram.rb", rlimit_as: 2 ** 28
Process.waitpid pid

Both of these are hard exits: unceremonious with no chance of clean up.

Softer limits

rlimit accepts an array with soft limit and hard limit

pid = Process.spawn "./heavy_cpu.rb", rlimit_cpu: [1,2]
Process.waitpid pid

We can respond to the soft limit by trapping XCPU (vs. hard limit, which cannot be trapped).

trap("XCPU") do
  puts "Received SIGXCPU, shutting down gracefully..."
  # Insert code to free resources, clear buffers etc.
  exit
end

Resources