2

I'm trying to write a "system sleep" script for systemd-suspend.service, to shutdown a user service before suspend (as it blocks suspending the kernel) and restart it after the system resumes.

The problem is that the system sleep script runs with system permissions, and I'm not sure how to address the user service - systemctl --user obviously doesn't work.

I've tried running su -c "systemctl --user stop <service>" <user> and USER=<user> systemctl --user stop <service> but both just get this error:

Failed to connect to bus: No such file or directory

The man page for systemctl doesn't offer much guidance about this issue.

slm
  • 369,824
Guss
  • 12,628

1 Answers1

3

After messing with this a bit, I found how to do this using sudo (or su - I'm using sudo as it can take a numeric UID which saves me the hassle of resolving the username):

XDG_RUNTIME_DIR=/run/user/<uid> sudo -E -u '#<uid>` systemctl --user status <service>.service

I'm assuming the UID is known and/or can be discovered easily from systemctl status user.slice.

Guss
  • 12,628
  • 1
    The reasons behind this bare magic incantation are much the same as at https://unix.stackexchange.com/a/407863/5132 , systemctl being a Desktop Bus client. – JdeBP Aug 22 '18 at 12:40
  • @JdeBP - thanks for explaining. I would also note that in this case of root trying to access a user's message bus, one might expect that it will be able to do it, but it looks like the message bus logic rejects any client with a different UID, not just non-privileged users. Hence the requirement for sudo. – Guss Aug 23 '18 at 16:08