Skip to content
systemcoding.dev
Systems Programming

Limit CPU seconds with RLIMIT_CPU and catch SIGXCPU

Cap the CPU time a process may use with setrlimit and RLIMIT_CPU on Linux 6.12, catch the SIGXCPU warning at the soft limit, and know when SIGKILL follows.

2 min read
Summarize in AI

A runaway loop in a plugin or a batch job should not burn a core forever. RLIMIT_CPU limits the CPU seconds a process may consume, and it has two stages. When the process reaches the soft limit, the kernel sends SIGXCPU, which you can catch to clean up. If it keeps running, it gets SIGXCPU again every second, until the hard limit, where SIGKILL ends it. See [setrlimit(2)](https://man7.org/linux/man-pages/man2/setrlimit.2.html).

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

static void on_xcpu(int sig) {
    (void)sig;
    write(1, "SIGXCPU: out of CPU budget\n", 27);
}

int main(void) {
    signal(SIGXCPU, on_xcpu);

    struct rlimit lim = { .rlim_cur = 1, .rlim_max = 3 };
    setrlimit(RLIMIT_CPU, &lim);

    for (;;) { }
}
Text
SIGXCPU: out of CPU budget
SIGXCPU: out of CPU budget
Killed

The soft limit of one CPU second fires the handler at 1 s and again at 2 s; at 3 s the hard limit is reached and the shell reports Killed. The count of handler lines can differ by one depending on where the tick falls.

The limit counts CPU time, not wall time: a process that sleeps or waits on I/O does not use it up, so it is no protection against a hang. It also covers all threads together. The handler only calls write, which is on the list of functions safe in a signal handler. A soft limit above the hard limit is rejected with EINVAL, and an unprivileged process can lower the hard limit but never raise it again.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 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.