Is there a programmatically way to limit duration, memory usage and run as less privileged user of a Linux program execution in C/C++ or Ruby ?
since system or `` can't do this.
sprintf(cmd_str,"/tmp/pro-%d < /tmp/in.txt > /tmp-%d.txt",id,id);
system(cmd_str); // in C
`/tmp/pro-#{id} < /tmp/in.txt > /tmp/out-#{id}.txt` // in Ruby
both statement makes that command run as the same user as the executor, uses whole processing power and memory as they like.
You'll want to use the
setrlimit
syscall to limit memory (Process::RLIMIT_AS
). To limit the runtime of the program, you can only control the total number of seconds a process gets CPU time (so that doesn't account for time spent sleeping or waiting on I/O). That's done withProcess::CPU
.Drop privileges with
Process::Sys.setgid
followed byProcess::Sys.setuid
after setting these rlimits, but before calling your target process withProcess::exec
.Example target program:
And accompanying Ruby script to invoke it (run this script as root with, e.g.
sudo /tmp/foo.rb
):And finally, output of running on my machine: