“Efficiently Manage Long-Running Processes Using the systemd-run”

sonu kushwaha
3 min readJul 12, 2024

--

In this post, we will look at how to daemonize long-running processes, tasks, or commands using systemd-run. One of the special features of this command is that it allows us to have complete control over the resources a particular process uses through control groups (cgroups).

Basic Usage

The basic syntax for systemd-run is as follows:

systemd-run  -u <service_file_name>  </path/to/exec/or/command>

For example:

sudo systemd-run -u sonu /usr/bin/sleep 300

In this example, we are running the sleep command for 300 seconds without any resource restrictions. now for handson will control few of the resources: CPU Quota, MemoryLimit,OOMPolicy. hence now will be seeing how to limit those with the adhoc commands.

Viewing all Parameters

To view all the parameters associated with the sonu service, you can use the following command:

systemctl show sonu  #this command will show all the parameters  to include  with -P flag

Applying Resource Limits

To limit resources such as CPU quota, memory, and Out-Of-Memory (OOM) policies, you can use the -p flag with systemd-run:

sudo systemd-run -u sonu \
-p MemoryLimit=10M \
-p CPUQuota=5% \
-p OOMPolicy=continue \
/usr/bin/sleep 300

With the above command, we set a memory limit of 10MB, a CPU quota of 5%, and specify that the process should continue running even if it encounters an OOM condition.

Observing Resource Control

After applying these settings, you can observe that the resources are now controlled as per the specified limits.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

The service file we have created is transient in nature, meaning it will exist only for the duration of the command. Once the command finishes execution, the service file will be removed.

reference

https://manpages.ubuntu.com/manpages/bionic/man1/systemd-run.1.html

--

--

sonu kushwaha
sonu kushwaha

Written by sonu kushwaha

open source enthusiast Docker, kubernetes

No responses yet