How to limit resource usage for a given process?

All we need is an easy explanation of the problem, so here it is.

I have a process for an application which needs to run, but ends up using far too much IO usage for what it does. And really crashes my computer, making it impossible to do anything else whilst it is running.

So I was wondering if there is a way to limit IO usage, RAM and CPU for a given process? And its sub-processes of course.

This is on my Ubuntu 18.04 LTS system.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You should use a combination of all cgexec, cpulimit and ionice:

  1. Limit RAM and SWAP:

    sudo cgcreate -g memory:/szMyGroup
    echo $(( 512 * 1024 * 1024 )) | sudo tee /sys/fs/cgroup/memory/szMyGroup/memory.limit_in_bytes
    echo $(( 1024 * 1024 * 1024 ))  | sudo tee /sys/fs/cgroup/memory/szMyGroup/memory.memsw.limit_in_bytes
    

    The above commands create a control group named szMyGroup (E.g. in your case group-great-uncle), set a cap to the processes run under szMyGroup up to 512 MB of physical memory and up to 1024 MB of swap and then:

    sudo cgexec -g memory:szMyGroup szMyProgram
    

    which will run your program under the szMyGroup control group, thus ensuring they adhere to the limits

  2. limit the disk IO:

    sudo ionice --class 3 --pid $(pgrep -f szMyProgram)
    

    The above command uses pgrep with reusing parts of the current command-line to limit its disk access to only use the disk when no other program is using it

  3. Limit the CPU:

    sudo cpulimit --limit=25 --pid=!#:4
    

    The program’s CPU is now limited to 25% of maximum

If the program does not use a lot of CPU to begin with, lower the value of cpulimit to half or less of what it currently uses.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply