I am building an online code editor for C and Java. Chances are users will write infinite loops. Is there any way I can limit the cpu and memory utilization of these processes at system level settings ?

My backend is a nodejs process which receives code from user , compiles it and runs it. I would like to kill the process when it exceeds some limits wrt cpu and memory.

1 Answer 1


Yes—the two main approaches are setrlimit(2) and (on Linux) control groups.

The main advantages of setrlimit is that it's simple and portable (specified by POSIX). You fork, then set limits for RLIMIT_AS and RLIMIT_CPU, then exec the code. The downside is that it's per-process, so the code could still fork to exceed the limit (each process it forks will get the same limit, but it's not shared). You could also set RLIMIT_NPROC to make fork fail (but of course, then code that needs to fork can't be tested).

The main advantage of control groups (cgroups) is that they can treat the process and all its children together—they get a combined limit. Downside is non-portability (Linux-only), and quite a bit more complexity. You may also have to talk to systemd, if it's managing control groups on your system. The best intro to cgroups is Neil Brown's Control Group Series on LWN.

Another approach is to run the code in a VM, which is then (at least in the case of KVM) a mostly ordinary process to the host. Much more heavyweight, but provides a lot of isolation.

Also, as a side note, you have a lot more things to worry about than infinite loops if you're running arbitrary untrusted code. You'd definitely not want someone to upload a spam bot, for example. I'd suggest looking at existing implementations, but AFAIK they're not open source.

  • thanks @derobert. if I go the VM way - should I use AWS instances and creates VM's on those servers ? would that be a good idea. I shall also explore Docker.
    – j10
    May 26, 2016 at 6:01
  • @jitenshah I don't know... Not sure if you can run your own VMs on AWS's VMs. Also don't know who's going to be most cost-effective, etc. Server Fault probably knows more about AWS, if you have specific sysadmin-type questions
    – derobert
    May 26, 2016 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.