8.5 getrlimit and setrlimit: Resource Limits

The getrlimit and setrlimit system calls allow a process to read and set limits on the system resources that it can consume. You may be familiar with the ulimit shell command, which enables you to restrict the resource usage of programs you run; [4] these system calls allow a program to do this programmatically.

[4] See the man page for your shell for more information about ulimit.

For each resource there are two limits, the hard limit and the soft limit. The soft limit may never exceed the hard limit, and only processes with superuser privilege may change the hard limit. Typically, an application program will reduce the soft limit to place a throttle on the resources it uses.

Both getrlimit and setrlimit take as arguments a code specifying the resource limit type and a pointer to a structrlimit variable. The getrlimit call fills the fields of this structure, while the setrlimit call changes the limit based on its contents. The rlimit structure has two fields: rlim_cur is the soft limit, and rlim_max is the hard limit.

Some of the most useful resource limits that may be changed are listed here, with their codes:

·         RLIMIT_CPU— The maximum CPU time, in seconds, used by a program. This is the amount of time that the program is actually executing on the CPU, which is not necessarily the same as wall-clock time. If the program exceeds this time limit, it is terminated with a SIGXCPU signal.

·         RLIMIT_DATA— The maximum amount of memory that a program can allocate for its data. Additional allocation beyond this limit will fail.

·         RLIMIT_NPROC— The maximum number of child processes that can be running for this user. If the process calls fork and too many processes belonging to this user are running on the system, fork fails.

·         RLIMIT_NOFILE— The maximum number of file descriptors that the process may have open at one time.

See the setrlimit man page for a full list of system resources.

The program in Listing 8.4 illustrates setting the limit on CPU time consumed by a program. It sets a 1-second CPU time limit and then spins in an infinite loop. Linux kills the process soon afterward, when it exceeds 1 second of CPU time.

Listing 8.4 (limit-cpu.c) CPU Time Limit Demonstration
#include <sys/resource.h> 
#include <sys/time.h> 
#include <unistd.h> 
 
int main () 
{
  struct rlimit rl; 
 
  /* Obtain the current limits. */ 
  getrlimit (RLIMIT_CPU, &rl); 
  /* Set a CPU limit of 1 second. */ 
  rl.rlim_cur = 1; 
  setrlimit (RLIMIT_CPU, &rl); 
  /* Do busy work. */ 
  while (1); 
 
  return 0; 
} 

When the program is terminated by SIGXCPU, the shell helpfully prints out a message interpreting the signal:

 
% ./limit_cpu 
CPU time limit exceeded