Resource limits on an exec()-ed process
anomit | June 25, 2009This might seem trivial at first sight but you have no idea how darn happy I’m to see this works
. So happy that I decided to blog about it. I already hear trumpets blowing in the distance.
Here is what I was worried about:
Normally, exec() is carried out in a forked process. Setting resource limits on a forked process is straightforward using setrlimit(). But I was apprehensive whether those limits would hold once I exec() another binary image within that forked process, and it wouldn’t be overstating it if I said I was about to front kick my laptop in joy
.
I tested by limiting the amount of CPU time(RLIMIT_CPU) that a running process is allocated since this would be the easiest to test IMO. The signal delivered to the process when it exceeds the CPU time limit is SIGXCPU.
Since this is all that is to it, wasting no more words, let’s get our hands dirty.
The program in which a process is forked and exec() is run (exec.c):
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
int pid;
int rv;
if (!( pid=fork() ))
{
struct rlimit limit;
getrlimit(RLIMIT_CPU, &limit);
limit.rlim_cur = 1;
setrlimit(RLIMIT_CPU, &limit);
execl("./inf","inf",NULL);
}
else if(pid)
{
wait(&rv);
}
else
printf("Error forking\n");
return 0;
}
The program whose binary image is specified in exec() (inf.c):
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void handler(int signum)
{
if (signum == SIGXCPU)
printf("Caught SIGXCPU signal, exec in peace\n");
}
int main()
{
signal(SIGXCPU, handler);
while(1);
return 0;
}
Now compile
$gcc -Wall exec.c -o exec
$gcc -Wall inf.c -o inf
and run
$./exec
You’ll see SIGXCPU being handled which means the resource limit is working!






