How do I prevent a runaway script from consuming all resources?

Quick Linux Tip #22:

Try: systemd-run --scope -p CPUQuota=25% -p MemoryMax=500M ./heavy_script.sh

Info: systemd-run creates a transient cgroup with resource limits. Any process launched inside respects those limits. Great for testing or running untrusted code.

Examples:

  • $ systemd-run --scope -p CPUQuota=50% stress --cpu 8
  • $ systemd-run --user -p MemoryMax=1G firefox
  • $ systemd-run --scope -p IOWeight=10 rsync -av /src /dst

Note: No installation needed on modern systems. Cleaner than cgcreate. Use --user for user services. IOWeight controls disk I/O priority.




LinuxTeck.com
linuxteck@ubuntu:~$ systemd-run --scope -p CPUQuota=25% -p MemoryMax=500M ./heavy_script.sh
Running scope as unit: run-r1a2b3c4d5.scope

linuxteck@ubuntu:~$ systemd-cgtop | grep run-r1a2
run-r1a2b3c4d5.scope    1    24.8%    487.3M    0B/s    0B/s
linuxteck@ubuntu:~$

PREVIOUS ARTICLE Quick Linux Tip #21: I can't unmount a disk because something's using it. How do I find what? NEXT ARTICLE Quick Linux Tip #23: How do I rename 500 photos with a consistent naming scheme?
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.