Search code examples
bashsystemdfish

How do I reliably check if I am inside systemd shell invoked by "systemd-run --shell"?


systemd-run provides --shell flag, that opens a new session. I often test high-memory applications and I use it like this:

systemd-run --slice=restrict_memory.slice --shell --user

Then, when I run an application and if it exceeds memory limit defined in restrict_memory.slice, OOM just kills this exact shell and I can continue with my work.

What I want is to reliably check if the shell I'm currently in is created through systemd-run --shell. Right now I check if SYSTEMD_EXEC_PID environment variable is greater than 2000 and display that I'm running inside systemd shell in the prompt (I use fish shell). I just noticed that this value is higher if I'm inside systemd shell, but I want a more reliable way to check this.

Tried googling this but did not find any results.


Solution

  • if grep -Fe /restrict-memory.slice/ /proc/self/cgroups; then
      echo "Running inside a restricted slice"
    else
      echo "NOT running inside a restricted slice"
    fi