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.
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).
#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 (;;) { }
}SIGXCPU: out of CPU budget
SIGXCPU: out of CPU budget
KilledThe 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.