Skip to content
systemcoding.dev
Systems Programming

Limit a Process's Resources with setrlimit

Cap open files, CPU time, memory and core dumps for a Linux process with setrlimit, understand soft and hard limits, and read the results in /proc.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Rust logos.

Every Linux process runs with a set of resource limits that the kernel enforces: how many files it may have open, how much CPU time it may use, how big a core dump may be, how much memory it may map. Most of the time you never notice them, until a server dies with Too many open files at 1,024 connections or a runaway loop is killed after ten CPU seconds. The calls that read and set them are getrlimit and setrlimit, and the same limits are what ulimit shows in a shell. This post explains soft and hard limits, builds working examples for the limits that matter most on Linux 6.12 with glibc 2.40, and shows how to see a running process's limits.

Soft and hard

Each resource has two numbers in a struct rlimit. The soft limit, rlim_cur, is the value the kernel enforces. The hard limit, rlim_max, is the ceiling for the soft limit. A process may lower or raise its soft limit freely up to the hard limit, may lower its hard limit (irreversibly), and may raise the hard limit only if it has the capability CAP_SYS_RESOURCE. The special value RLIM_INFINITY means no limit.

The design lets a login configuration set a conservative soft limit and a higher hard limit, so a program that needs more can raise itself without privilege, while a program that wants to be locked down lowers both.

show_limit.cc
#include <stdio.h>
#include <sys/resource.h>

static void show(const char *name, int resource)
{
    struct rlimit rl;
    if (getrlimit(resource, &rl) == -1) {
        perror(name);
        return;
    }
    printf("%-14s soft=", name);
    if (rl.rlim_cur == RLIM_INFINITY)
        printf("unlimited");
    else
        printf("%llu", (unsigned long long)rl.rlim_cur);
    printf(" hard=");
    if (rl.rlim_max == RLIM_INFINITY)
        printf("unlimited\n");
    else
        printf("%llu\n", (unsigned long long)rl.rlim_max);
}

int main(void)
{
    show("RLIMIT_NOFILE", RLIMIT_NOFILE);
    show("RLIMIT_CORE", RLIMIT_CORE);
    show("RLIMIT_STACK", RLIMIT_STACK);
    show("RLIMIT_NPROC", RLIMIT_NPROC);
    show("RLIMIT_CPU", RLIMIT_CPU);
    return 0;
}
Shell
gcc -std=gnu17 -O2 -Wall -o show_limit show_limit.c
./show_limit
Text
RLIMIT_NOFILE  soft=1024 hard=1048576
RLIMIT_CORE    soft=0 hard=unlimited
RLIMIT_STACK   soft=8388608 hard=unlimited
RLIMIT_NPROC   soft=63547 hard=63547
RLIMIT_CPU     soft=unlimited hard=unlimited

The values are a typical desktop configuration and differ per system. The stack limit is in bytes, the core limit of 0 means no core files are written, and the file descriptor limit has a soft value of 1,024 with a much larger hard value. That gap is why a server can raise its own limit to the hard value at startup with no privilege.

Raise the file descriptor limit

A network server that accepts many connections needs more than 1,024 descriptors, and the standard fix is to raise the soft limit to the hard limit at startup:

raise_nofile.cc
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>

int main(void)
{
    struct rlimit rl;
    getrlimit(RLIMIT_NOFILE, &rl);
    printf("before: soft=%llu hard=%llu\n",
           (unsigned long long)rl.rlim_cur, (unsigned long long)rl.rlim_max);

    rl.rlim_cur = rl.rlim_max;
    if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
        printf("setrlimit failed: %s\n", strerror(errno));
        return 1;
    }

    getrlimit(RLIMIT_NOFILE, &rl);
    printf("after:  soft=%llu hard=%llu\n",
           (unsigned long long)rl.rlim_cur, (unsigned long long)rl.rlim_max);
    return 0;
}
Text
before: soft=1024 hard=1048576
after:  soft=1048576 hard=1048576

Raising the soft limit to the hard one needs no privilege. If a service manager runs the program, remember that systemd sets its own LimitNOFILE=, so the hard limit the program sees is whatever the unit allows. One more detail: the kernel also has a system wide cap in /proc/sys/fs/nr_open, and a limit above it fails with EPERM.

See the limit hit

Lower the descriptor limit and open files until the call fails, to see what the error looks like and what the program must handle:

hit_limit.cc
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>

int main(void)
{
    struct rlimit rl = { .rlim_cur = 8, .rlim_max = 8 };
    if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
        perror("setrlimit");
        return 1;
    }

    int opened = 0;
    for (;;) {
        int fd = open("/dev/null", O_RDONLY);
        if (fd == -1) {
            printf("open failed after %d files: %s\n", opened, strerror(errno));
            break;
        }
        opened++;
    }
    return 0;
}
Text
open failed after 5 files: Too many open files

The limit is 8 descriptors, and three are already taken by standard input, output and error, so five more succeed and the sixth fails with EMFILE, whose text is Too many open files. That is the exact message that appears in server logs when a limit is too low. Notice the program set both soft and hard to 8, so it cannot raise the limit again, which is the one way limits become permanent for a process and its children.

The limits that matter

ConstantLimitsWhat happens at the limit
RLIMIT_NOFILEHighest descriptor number plus oneopen, socket, accept fail with EMFILE
RLIMIT_CPUCPU secondsSIGXCPU at the soft limit, SIGKILL at the hard limit
RLIMIT_ASSize of the virtual address space in bytesmmap, brk and malloc fail with ENOMEM
RLIMIT_DATASize of the data segment and heapbrk fails with ENOMEM
RLIMIT_STACKSize of the main thread's stackStack overflow gets SIGSEGV
RLIMIT_CORESize of a core dump file0 disables core files
RLIMIT_FSIZELargest file the process may createSIGXFSZ, then write fails with EFBIG
RLIMIT_NPROCProcesses for the user (counted by real UID)fork fails with EAGAIN
RLIMIT_MEMLOCKBytes of locked memorymlock fails with ENOMEM or EPERM

RLIMIT_AS is a blunt tool for memory: it counts address space, not resident memory, and a program that maps large sparse files or reserves address space trips it long before it uses real memory. For limiting actual memory use, control groups (the memory controller) are the correct tool, and the posts on cgroups in this series cover it.

RLIMIT_CPU is useful for untrusted or runaway computation. With a soft limit of 2 seconds and a hard limit of 4, the process receives SIGXCPU after two seconds of CPU, which it may catch and use to save state, and SIGKILL after four if it keeps running.

Reading a running process's limits

You do not have to write code to inspect limits. The file /proc/<pid>/limits shows every limit of any process you can inspect, with the soft and hard values and the units:

Shell
cat /proc/self/limits | head -n 6
Text
Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes

The values are an example from one machine. For a service whose behavior you doubt, read this file from the service's pid, since limits are per process and inherited from the parent. For a different process you can also change them from outside with the prlimit command, which wraps the prlimit(2) system call: prlimit --pid 2417 --nofile=65536:65536 sets both limits on a running process, and needs CAP_SYS_RESOURCE to raise a hard limit or to change another user's process.

Catching SIGXCPU

A process that exceeds its soft CPU limit is not killed at once. The kernel sends SIGXCPU, and then repeats it every second until the hard limit, where SIGKILL ends the process. A handler can use the grace period to write a checkpoint or flush a log. Keep the handler small, since it runs asynchronously, and set a flag that the main loop reads:

cpu_limit.cc
#include <signal.h>
#include <stdio.h>
#include <sys/resource.h>
#include <unistd.h>

static volatile sig_atomic_t over_budget;

static void on_xcpu(int sig)
{
    (void)sig;
    over_budget = 1;
}

int main(void)
{
    struct rlimit rl = { .rlim_cur = 1, .rlim_max = 3 };
    setrlimit(RLIMIT_CPU, &rl);

    struct sigaction sa = { .sa_handler = on_xcpu };
    sigaction(SIGXCPU, &sa, NULL);

    volatile unsigned long sum = 0;
    while (!over_budget)
        sum++;

    puts("soft CPU limit reached, shutting down cleanly");
    return 0;
}
Text
soft CPU limit reached, shutting down cleanly

The loop burns CPU until one second of processor time has passed, the kernel delivers SIGXCPU, the handler sets the flag and the program exits normally. Had it ignored the signal, it would have been killed after three seconds of CPU. The measure is CPU time and not wall time, so a program that sleeps never trips it.

In a shell and a service

The shell builtin ulimit reads and sets the same limits for the shell and its children. ulimit -n prints the soft file descriptor limit, ulimit -Hn the hard one, and ulimit -n 4096 sets the soft limit for the current shell. Persistent per user settings live in /etc/security/limits.conf and /etc/security/limits.d/, applied by PAM at login, which does not apply to services started by systemd. For a service, set LimitNOFILE=65536 or LimitCORE=0 in the unit file.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.