7

How do I run a command in a different already existing systemd session or scope?

As far as I can tell there is no difference between a session and the session's scope unit, as far as processes being in one or the other is concerned.

This question comes up because in Gnome, commands run from the terminal are seen as part of the gnome-terminal-server.service, not as part of the session-xx.scope. If I want to run a command in my session (or in another session for that matter) how do I do that?

(NB: this is the reverse of this question, which asks to create a new scope around existing processes.)

1
  • 1
    Looking at the available methods via busctl --user introspect org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager, you may have success with AttachProcessesToUnit. I couldn't get it to work myself, sadly. Commented Sep 18, 2020 at 15:01

1 Answer 1

2

@GammaFunction points to the right direction, and I managed to succeed with the following command:

$ systemd-run --user --scope --unit="app-sleep" --property=Delegate=yes sleep 9999 &
$ disown
$ sleep 8888 &
$ pid=$(jobs -p)
$ busctl --user call org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager AttachProcessesToUnit ssau "app-sleep.scope" / 1 "$pid"

The ssau (I think it means string, string, array of unsigned) here denotes the parameter types passed to function AttachProcessesToUnit, the documentation of this function can be found in man:org.freedesktop.systemd1(5).

Notes:

  1. The unit to be attached should set Delegate=yes (see man:systemd.resource-control(5))
  2. To pass an array of pids, you should pass the length of the array before the pids (which is 1 in the above example).

After attaching it to the given scope, you can see the scope's child processes via systemd-cgls or systemctl --user status app-sleep.scope.

1
  • Thanks for solving this puzzle and posting the solution. I have looked everywhere and this is the only thing that worked.
    – likebike
    Commented Apr 26, 2023 at 17:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .